The only difference I can see between designated and convenience initialisers is that the former necessarily calls a super class init (if available).
I don't understand then why I can't add a designated init to a class in an extension, while adding a convenience one is OK.
Why is it so bad to have an init from an extension to possibly call a super class initialiser?
Extensions can add new computed properties, but they can't add stored properties, or add property observers to existing properties.
Designated initializers are the primary initializers for a class. A designated initializer fully initializes all properties introduced by that class and calls an appropriate superclass initializer to continue the initialization process up the superclass chain.
Swift defines two kinds of initializers for class types to help ensure all stored properties receive an initial value. Designated initializers are the primary initializers for a class.
Extensions let us add functionality to classes, structs, and more, which is helpful for modifying types we don't own – types that were written by Apple or someone else, for example.
Let's recall what a designated initializer is.
A designated initializer fully initializes all properties introduced by that class and calls an appropriate superclass initializer to continue the initialization process up the superclass chain.
Excerpt From: Apple Inc. “The Swift Programming Language.”
class ClassA {
private let propertyA: Int
init(propertyA: Int) {
self.propertyA = propertyA
}
}
class ClassB: ClassA {
private let propertyB: Int
init(propertyA: Int, propertyB: Int) {
self.propertyB = propertyB
super.init(propertyA: propertyA)
}
}
extension ClassB {
// If this was a designated initializer, you need to initialize propertyB before calling a superclass initializer.
// But propertyB is a private property that you can't access.
// If you don't have the source code of ClassB, you will not even know there is a property called propertyB.
// This is why we can't use extensions to add designated initializers.
init(propertyC: Int) {
...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With