In swift there is the concept of designated initializer (which is the "normal" constructor we know from other languages, I assume).
But there is also something called Convenience Initializer, which I do understand how to write, but the point is lost on me.
As, If I understand correctly, you can achieve the same thing without writing the keyword convenience
, or not?
Actually it's very easy to understand them: they are initializers with default parameters.
From the docs:
Convenience initializers are secondary, supporting initializers for a class. You can define a convenience initializer to call a designated initializer from the same class as the convenience initializer with some of the designated initializer’s parameters set to default values. You can also define a convenience initializer to create an instance of that class for a specific use case or input value type.
Example:
class A {
var a: Int
var b : Int
init() {
a = 0
b = 0
}
/*convenience*/ init(a: Int) {
self.init()
self.a = a
}
}
In the above case, you cannot call self.init()
, you have mark your initializer with the convenience
keyword, otherwise it will be a compiler error. So you cannot chain two designated initializer from the same class.