The primary initializer for a class is a Designated initializer. It initializes all the properties of a class and calls a superclass initializer to continue the initialization process. Whereas Convenience init is a secondary initializer of a class. In the same class, we can define a Convenience initializer to call a designated initializer. It is not necessary to provide a Convenience initializer, if it is required then only we will use it.
The syntax for Convenience init is:
1 2 3 |
convenience init(parameters) { // code } |
According to swift doc, there are three rules that simplify the relationships between designated and convenience initializers.
1 -> A Designated initializer must call a designated initializer from its immediate superclass.
2-> A convenience initializer must call another initializer from the same class.
3-> A Convenience initializer must ultimately call a designated initializer.
Let’s see an example of using Convenience init.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
class Person{ var name:String var salary:Double? init(){ self.name = "None" } convenience init(salary:Double){ self.init() self.salary = salary } } let p1 = Person() print(p1.name) //None print(p1.salary ?? 0) // 0 let p2 = Person(salary: 50000) print(p2.name)// None print(p2.salary ?? 0)// 50000.0 |
In the above example. We have created a Person class. In the Designated initializers we have initialized the name with the value “none”. Now we have created a convenience init with a parameter salary. So, now when we use convenience init then it confirms that all the properties must be initialized, by calling the Designated init. So, in this way, we do not have to write the initialization code again.
Thanks for reading this blog.
You can also check other blogs from here. If you have any issues, queries, or suggestions then you can leave your issues/queries/suggestions in the comment section.