swift - How to make a method in superclass create subclass objects? -
class car { func upgrade() -> car { return car() } } class racingcar : car { } let racingcar = racingcar() let upgradedracingcar = racingcar.upgrade() // ideally upgradedracingcar should racingcar
how make upgrade method create racingcar objects if called on subclass, without implementing in racingcar?
like this. if it's class method:
class car { class func upgrade() -> self { return self() } }
if it's instance method:
class car { func upgrade() -> self { return self.dynamictype() } }
the return type self
means "the class of me, polymorphically". return car if car , racingcar if racingcar. notation self()
, self.dynamictype()
shorthand calling init
; these both classes, that's legal. presume have more elaborate initializer. have make initializer required
calm fears of compiler (as explain here); thus, neither of above compile unless init()
marked required
in car.
Comments
Post a Comment