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:

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 💚💚💚💚💚💚 !!!!


iOS and tvOS developer, dreamer, photographer 🤨

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store