class - Swift Generics, create derived object -
i have store class coded generic, can manage kind of classes derived common base class.
the store has new() method, creates , returns class manages. in theory, should return derived class.
unfortunately, store returns base class. here code snippet explains it:
import uikit class base: nsobject { var id:int=0 } class adress:base { var name = "" } class store<t:base> { var nextid:int = 0 func getnextid()->int { return ++nextid; } func new() ->t{ let n = t() n.id = getnextid() return n } } let store = store<adress>() var adr:adress = store.new() // should adress, base adr.name = "tom" // crash here, because adr not adress
if debug new() method inside store, creates adress object. in calling code, base object.
any idea whats going wrong here?
i not understand intensions above code. if substitute
class store<t: base> {
by
class store<t: adress> {
then variable adr of type adress. following statements work then
println(adr.name) // displays "tom" println(adr.id) // displays "1"
Comments
Post a Comment