(This answer is up to date with Swift 3)
Placing the default parameter value in a convenience initializer, overriding the designated initializer onto which this convenience initializer points
You can let the public superclass initializer with a default argument be a convenience
initializer, one that will be used as initializer "interface" for the superclass as well as the subclass. This convenience initializer in turn simply calls a fileprivate
designated initializer which is the one you override in your subclass. E.g.
public class A {
let a: String
/* public initializer */
public convenience init(a: String = "aaaa") {
self.init(b: a)
}
/* "back-end" fileprivate initializer: implement initializer
logic here, and override this initializer in subclasses */
fileprivate init(b: String) {
self.a = b
print("super:", b)
}
}
public class B: A {
let b: String
override fileprivate init(b: String) {
self.b = "sub_" + b
print("sub:", b)
super.init(b: b)
}
}
/* The following initializations all call the convenience initializer defined in A */
let a = A() // prints> super: aaaa
let b = B() // prints> sub: aaaa, super: aaaa
let c = B(a: "foo") // prints> sub: foo, super: foo
print(a.a) // aaaa
print(b.a) // aaaa
print(b.b) // sub_aaaa
print(c.a) // foo
print(c.b) // sub_foo
In this simple example the subclass overrides all designated initializers of its superclass (here: one designated initializer), which is why also all the convenience initializers of its superclass (here: one) are available (inherited) by the subclass, as described by Rule 2 in the Language Guide - Initialization - Class Inheritance and Initialization - Automatic Initializer Inheritance.
Rule 1
If your subclass doesn’t define any designated initializers, it
automatically inherits all of its superclass designated initializers.
Rule 2
If 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—then it
automatically inherits all of the superclass convenience initializers.