3

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.

Evan
  • 430
  • 6
  • 16

1 Answers1

4

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
    }
}
Nicolas Miari
  • 16,006
  • 8
  • 81
  • 189
  • Thank you for your help. It makes sense, but I still have a question. Are all methods and properties defined in superclass available for subclass?@NicolasMiari – Evan Mar 10 '16 at 03:41
  • Yes, unless they are declared as `private`. But even then, they are still available if both superclass and subclass are defined in the same file (in swift, access control is source file-based) – Nicolas Miari Mar 10 '16 at 03:45
  • There are special rules regarding **initializers** (like you mention in your question), but other methods are inherited automatically. – Nicolas Miari Mar 10 '16 at 03:47
  • Thanks again. Nice to have you here.@NicolasMiari – Evan Mar 10 '16 at 03:48
  • I myself am still quite new to swift too, and my answer might not be 100% correct. I suggest you wait a little while before accepting it. Something more deserving of it might come along. – Nicolas Miari Mar 10 '16 at 03:49