Reputation: 40068
The Swift documentation states the following:
If the initializer you are overriding is a convenience initializer, your override must call another designated initializer from its own subclass, as per the rules described above in Initializer Chaining.
This means, that when I define an initializer with the same signature as a convenience
initializer from the base class, then it must also act as a convenience
initializer. I cannot "override" a convenience
initializer with a designated
initializer.
This seems awkward to me: There might be various cases where a signature, e.g., (String)
is only a convenience init for the base class but a designated init for a subclass. In contrast to methods, only because two initializer have the same signature, they do not have to perform a similar task. A signature of (String)
could mean something completely different for a subclass.
Upvotes: 4
Views: 3403
Reputation: 1937
What they mean is that if the initialiser that you have after overriding is a convenience initialiser, then you must follow Initialiser Chaining.
The following works fine meaning you can override a convenience initialiser with a designated initialiser :
class Base {
var x = 0
init() {}
convenience init(_: Int) {
self.init()
self.x = 5
}
}
class Derived : Base {
init() {}
init(_: Int) {
super.init()
self.x = 10
}
}
var i = Derived(1) // x = 10
Upvotes: 3