Required Initializers in swift

Hemant Soni
2 min readSep 8, 2019

Required initializers will be explained in this article.

If we write a required modifier before the definition of init method in a class that indicates that every subclass of that class must implement that initializer.

There are various things related to required initializer.

Lets Consider the following example:

As you can see there is super class named ClassA and derived class named ClassB. Here we didn’t write required init method in ClassB because there is no requirement of ClassB to do something in init() method, So it will automatically call super class required init().

Note: You do not have to provide an explicit implementation of a required initializer if you can satisfy the requirement with an inherited initializer.

Lets change something in above code snippet to understand other things related to required init() method —

On the above example we have written required init() in derived class so at the time of initialization of ClassB’s object, Super class required initializer method will automatically get called and we don’t need to write super.init() method .

Note — Here we didn’t write super.init() in ClassB required init() method.

Lets modify above code snippet to understand when we need to call super init() method in derived class initializer.

Now we are getting an error :- “‘super.init’ isn’t called on all paths before returning from initializer”

It means, if there is any parameter in required init() method of super class then we have to call super.init() method in ClassB’s required init() method.

Finally we know now all about required init() method in Swift.

If you enjoyed reading this post and found it useful, please share and recommend it so others can find it !!!!

Thanks!!

--

--