swift - Storing and generating instance of classes using generics -
so want create instances conforms specific protocol. want create either instances of or class conforms testprotocol. can't run code in playground, wonder whats wrong? or better, how should solved?
protocol testprotocol { init(value: int) } class : testprotocol { init() {} required init(value: int) { } } func generatewithinstances<t : testprotocol>(item: t, #numberofinstances: int) -> [t] { var list: [t] = [] index in 1...numberofinstances { list.append(t(value: index)) } homecoming list } var list: [testprotocol] = [] allow instanceofa = a() list.extend(generatewithinstances(instanceofa, numberofinstances: 10))
update
array
extend
s doesn't back upwards polymorphism (both arrays before , after extends must of same type).
extension array { ... mutating func extend<s : sequencetype t == t>(newelements: s) ... }
it's bug in swift code crashes compiler or playground. (a helpful error message should provided.)
as you've noted in update, reason it's not working generatewithinstances
returns array of a
s ([a]
), , extend
requires a
identical testprotocol
:
instances
cannot casted [testprotocol]
since testprotocol
not subtype of a
.
however, can set objects in 1 @ time using append
:
for obj in instances { list.append(obj) }
you write extension array
doesn't require type equality.
generics swift
No comments:
Post a Comment