Initializers in swift part-3: Required Initializers in swift

Required initializers will be explained in this article.

Here is the first part of this article series: Initializers in swift part-1 : (intro, convenience and designated intializers)

Here is the second part: Initializers in swift part-2: Failable Initializers in swift

Write the required modifier before the definition of a class initializer to indicate that every subclass of the class must implement that initializer.

You must also write the required modifier before every subclass implementation of a required initializer, to indicate that the initializer requirement applies to further subclasses in the chain. You do not write the override modifier when overriding a required designated initializer:

Consider the following example:

//required initclass classA {required init() {var a = 10print(a)}}class classB: classA {required init() {var b = 30print(b)}}//______________________let objA = classA()let objB = classB()prints:
10
30
10
//______________________

Let there be another class classC .

class classC: classA { }
//______________________
let objC = classC() // prints 10 ..superclass init method gets called.

Note: You do not have to provide an explicit implementation of a required initializer if you can satisfy the requirement with an inherited initializer. In the above class classC , since we don’t have any stored properties unintialized at the time of initialization, we dont have to declare the required init explicitly.

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

Thanks!!

iOS and tvOS developer, dreamer, photographer 🤨

iOS and tvOS developer, dreamer, photographer 🤨