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

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -