Convenience Init In Swift

Khuong Pham
Indie Goodies
Published in
2 min readMay 23, 2017

--

Classes, structures and enumerations need at least one empty init method to initialize for preparing their instances.

For Structures and Enumerations, their constructor already have declared implicitly.

About the Classes, if we write a class, we should declare it explicitly.

Ok, it’s good, right?

But a class has Inheritance, that means it can inherit its super class methods, properties, and other characteristics. Let’s move on to next code below

We have a class B - a subclass of class A. We added a variable, and we added an initializer to set a value to b so it'll compile. You might expect that B has inherited A's initializer, init(a: Int). But it doesn't. How does A's init(a: Int) know how to assign a value to the b variable that B added? It doesn't. So we can't initialize a Binstance with an initializer that can’t initialize all of our values, like so:

So If I only want to initialize a or b value, with a default value of the rest. How could it?

Convenience init will help us, add this code

So we have a very convenience way to initialize a Binstance.

That’s it! I hope you enjoy this article, thanks for reading and I will see you next time.

Support my apps

https://indiegoodies.com/breather

--

--