Why use required Initializers in Swift classes?

SwiftInitialization

Swift Problem Overview


I am trying to understand the use of the required keyword in Swift classes.

class SomeClass 
{
    required init() {
        // initializer implementation goes here
    }
}

required doesn't force me to implement the method in my child-class. If I want to override the required designated initializer of my parent class I need to write required and not override. I know how it works but can not understand why I should do this.

What is the benefit of required? As far as I can tell, languages like C# don't have something like this and work just fine with override.

Swift Solutions


Solution 1 - Swift

It's actually just a way of satisfying the compiler to assure it that if this class were to have any subclasses, they would inherit or implement this same initializer. There is doubt on this point, because of the rule that if a subclass has a designated initializer of its own, no initializers from the superclass are inherited. Thus it is possible for a superclass to have an initializer and the subclass not to have it. required overcomes that possibility.

One situation where the compiler needs to be satisfied in this way involves protocols, and works like this:

protocol Flier {
    init()
}
class Bird: Flier {
    init() {} // compile error
}

The problem is that if Bird had a subclass, that subclass would have to implement or inherit init, and you have not guaranteed that. Marking Bird's init as required does guarantee it.

Alternatively, you could mark Bird as final, thus guaranteeing the converse, namely that it will never have a subclass.

Another situation is where you have a factory method that can make a class or its subclass by calling the same initializer:

class Dog {
    var name: String
    init(name: String) {
        self.name = name
    }
}

class NoisyDog: Dog {

}

func dogMakerAndNamer(whattype: Dog.Type) -> Dog {
    let d = whattype.init(name: "Fido") // compile error
    return d
}

dogMakerAndNamer is calling the init(name:) initializer on Dog or a Dog subclass. But how can the compiler be sure that a subclass will have an init(name:) initializer? The required designation calms the compiler's fears.

Solution 2 - Swift

I want to draw an attention on another solution provided by Required, apart from Matt has given above.

class superClass{
    var name: String
    required init(){
        // initializer implementation goes here
        self.name = "Untitled"
    }
}
class subClass: superClass {
    var neakName: String = "Subclass Untitled"
    
}
let instanceSubClass = subClass()
instanceSubClass.name        //output: "Untitled"
instanceSubClass.neakName    //output: "Subclass Untitled"

As you can check in above example, I've declared required init() on superClass, init() initializer of superClass has inherited by default on subClass, So you able to create an instance of subClass let instanceSubClass = subClass().

But, suppose you want to to add one designated initializer on subClass to assign run time value to stored property neakName. Of course you can add it, but that will result to no initializers from the superClass will be inherited to subClass, So if you will create an instance of subClass you will create through its own designated initializer as below.

class superClass{
    var name: String
    init(){
        // initializer implementation goes here
        self.name = "Untitled"
    }
}
class subClass: superClass {
    var neakName: String = "Subclass Untitled"
    init(neakName: String) {
        self.neakName = neakName
    }
}
let instanceSubClass = subClass(neakName: "Bobby")
instanceSubClass.name       //output: "Untitled"
instanceSubClass.neakName   //output: "Bobby"

Here above, you won't be able to create an instance of subClass by just subClass(), But if you want that every subclasses of superClass must have their own init() initializer to create direct instance by subClass(). Just place required keyword before init() on superClass, it will force you to add init() initializer on subClass too - as below.

class superClass{
    var name: String
    required init(){
        // initializer implementation goes here
        self.name = "Untitled"
    }
}
class subClass: superClass {
    var neakName: String = "Subclass Untitled"
    init(neakName: String) {
        self.neakName = neakName
    }
}    // Compiler error <------------ required `init()` must be provided by subClass.
let instanceSubClass = subClass(neakName: "Bobby")
instanceSubClass.name       //output: "Untitled"
instanceSubClass.neakName   //output: "Bobby"  

SO, use required keyword before initializer on superclass, when you want all subclasses must have been implemented required initializer of superclass.

Solution 3 - Swift

According to the documentation:

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

So yes, required does force all child classes to implement this constructor. However, this is not needed

 if you can satisfy the requirement with an inherited initializer.

So if you have created more complex classes that cannot be fully initialized with a parent constructor, you must implement the require constructor.

Example from documentation (with some added stuff):

class SomeClass {
    required init() {
        // initializer implementation goes here
    }
}

class SomeSubclass: SomeClass {
    let thisNeedsToBeInitialized: String
    required init() {
        // subclass implementation of the required initializer goes here
        self.thisNeedsToBeInitialized = "default value"
    }
}

Solution 4 - Swift

If you are trying to add you own initialiser in the sub class, then you have to follow certain things those were declared in super class. So it make sure that you will not forget to implement that required method. If you forget compiler will give you error // fatal error, we've not included the required init(). Another reason is it creates a set of conditions that ever sub class should follow it the sub class is defining its own initialiser.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTalkingCodeView Question on Stackoverflow
Solution 1 - SwiftmattView Answer on Stackoverflow
Solution 2 - SwiftKiran JasvaneeView Answer on Stackoverflow
Solution 3 - Swiftpseudonym117View Answer on Stackoverflow
Solution 4 - SwiftAmit89View Answer on Stackoverflow