Evan
Evan

Reputation: 442

Swift Inheritance v.s calling super

I was learning the following chapter in The Swift Programming Languages:

If your subclass doesn’t define any designated initializers, it automatically inherits all of its superclass designated initializers.

Then I tried these codes in my target:

class Car {
    var name: String = "Unknown"
    init(name: String) {
        self.name = name
    }
}
class RacingCar: Car {
    var speed = 0.0
    init(name: String, speed: Double) {
        self.speed = speed
        super.init(name: name)//this is where I got confused
    }
}

According to rule one, RacingCar class won't inherit the init(name:) designated initializer from its superclass Car. However, I'm still able to call the super.init(name:) in my subclass. How could that happen? I'm so confused about this. Can anyone explain why? Thanks.

Upvotes: 3

Views: 4948

Answers (1)

Nicolas Miari
Nicolas Miari

Reputation: 16256

Inheriting a initializer means that that initializer is made available to instances of your subclass (that's what inheritance means); that is, your subclass' initializer can call it on self:

class RacingCar: Car {
    var speed = 0.0
    init(name: String, speed: Double) {
        self.speed = speed
        self.init(name: name) // <-- Error: This initializer is not inherited
    }
}

You don't need to inherit an initializer to call it on super: The superclass does not lose access to its initializer just because you subclassed it.

class RacingCar: Car {
    var speed = 0.0
    init(name: String, speed: Double) {
        self.speed = speed
        super.init(name: name) // <-- Works: super class does have this initializer
    }
}

Upvotes: 4

Related Questions