How to create a method in a superclass, create subclass objects?

class Car {
     func upgrade() -> Car { 
        return Car()
     }
}


class RacingCar : Car {

}

let racingCar = RacingCar()
let upgradedRacingCar = racingCar.upgrade()
// ideally upgradedRacingCar should be a RacingCar

      

How do I make an update method to create RacingCar objects when called in a subclass without implementing it in RacingCar?

+3


source to share


1 answer


Like it. If it's a class method:

class Car {
    class func upgrade() -> Self { 
        return self()
    }
}

      

If it's an instance method:



class Car {
    func upgrade() -> Self { 
        return self.dynamicType()
    }
}

      

The return type Self

means "class me, polymorphic". Therefore, we return the car if it is a car and a racing car if it is a RacingCar. Designations self()

and self.dynamicType()

are an abbreviation for a call init

; these are both classes, so legal. I suppose you will have a more complex initializer. You will need to make your initializer required

to allay compiler concerns (as I explain here ); thus none of the above will compile if unchecked init()

required

.

+5


source







All Articles