Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 488
Evan Avatar asked Mar 24 '26 22:03

Evan


1 Answers

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
    }
}
like image 136
Nicolas Miari Avatar answered Mar 27 '26 10:03

Nicolas Miari



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!