In Swift, a subclass does not automatically inherit its superclass's initialisers. If, however, you do want to a subclass to provide one or more of the same initialisers as its superclass, you can provide a custom implementation of those initialisers within the subclass.
If, however, you want to provide the same form as a superclass's designated initialiser, you are effectively overriding that initialiser. As a result, you have to include the override
keyword. This is true even if you are overriding an automatically provided default initialiser.
In the example below, we introduce a class Vehicle
. Because it provides a default value to all its stored properties, it is given a default initialiser:
class Vehicle {
var numberOfWheels = 0
var description: String {
return "\(numberOfWheels) wheel(s)"
}
}
let vehicle = Vehicle()
print("Vehicle: \(vehicle.description)")
// Vehicle: 0 wheel(s)
If we now provide a subclass Bicycle
with an empty initialiser (var bike = Bicycle()
), it will be overriding Vehicle's initialiser, so it needs to be defined using the override
keyword.
class Bicycle: Vehicle {
override init() {
super.init()
numberOfWheels = 2
}
}
let bicycle = Bicycle()
print("Bicycle: \(bicycle.description)")
// Bicycle: 2 wheel(s)
While a subclass doesn't automatically inherit its superclass's initialiser, it does if certain conditions are met.
Assuming you have provided default values for any new stored properties the subclass introduced, initialisers are automatically inherited if:
- Your subclass doesn’t define any designated initializers
OR
- Your subclass provides an implementation of all of its superclass designated initializers—either by inheriting them as per rule 1, or by providing a custom implementation as part of its definition. In this case, it automatically inherits all of the superclass convenience initializers.