I am having troubles to understand the difference between both, or the purpose of the convenience init
.
All answers are sounds good but, lets understand it with an simple example
class X{
var temp1
init(a: Int){
self.temp1 = a
}
Now, we know a class can inherit another class, So
class Z: X{
var temp2
init(a: Int, b: Int){
self.temp2 = b
super.init(a: a)
}
Now, in this case while creating instance for class Z, you will have to provide both values 'a' and 'b'.
let z = Z(a: 1, b: 2)
But, what if you only want to pass b's value and want rest to take default value for others, then in that case you need to initialise other values a default value. But wait how?, for that U need to set it well before in the class only.
//This is inside the class Z, so consider it inside class Z's declaration
convenience init(b: Int){
self.init(a: 0, b: b)
}
convenience init(){
self.init(a: 0, b: 0)
}
And now, you can create class Z's instances with providing some, all or none values for the variables.
let z1 = Z(b: 2)
let z2 = Z()