How to Initialize a Swift Subclass that Has Declared a Designated Initializer
When a subclass defines its own designated initializer, it loses the ability to inherit initializers — self.init( ) — from its superclass.
Instead, the designated initializer must call one of the superclass’s designated initializers using super.init().
Let’s see this in action!
class User {
var name: String
var location: String
init(name: String, location: String) {
self.name = name
self.location = location
}
convenience init(location: String) {
self.init(name: "Ijeoma", location: location)
}
}
class Subscriber: User {
init(name: String) {
super.init(name: name, location: "London")
}
}
In this code, the User class has a name and location property of type String, an explicit designated initializer that initializes both stored properties and a convenience initializer that accepts a location parameter.
Within the convenience initializer, self.init() is invoked with the value "Ijeoma" passed as the argument for name, and the location parameter passed as the argument for self.location — from the superclass.
Next, a Subscriber class is declared and it inherits from the User class.
Inside the Subscriber class, an explicit designated initializer is declared — and it makes a call to super.init( ) of the superclass.
Because the Subscriber class has declared its own explicit designated initializer, all initializer inheritance is cut off.
The only way Subscriber can create an instance is by using its designated initializer, which calls super.init( ) — the designated initializer of its superclass.
let newsletterSubscriber = Subscriber(name: "Fiona")
This code uses the Subscriber class’ designated initializer which makes a call to super.init( ).
An exception to this rule occurs when the subclass’s designated initializer overrides all of the superclass’s designated initializers. In such a case, the subclass will inherit the superclass’s convenience initializers.