Check Mobile App
Read now
Start a Project

Convenience init in swift

Save

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:

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.

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.

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

css.php

Great Product, Great Team, and Great Support Service. And if you want to add more features to the product, they can submit any idea that comes to your mind. They really care about their clients and we are really happy and honored to deal with Webkul.

Osama
Talk to Sales

Global

Live Chat
Start a Project

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home