Why use required Initializers in Swift classes?

前端 未结 4 603
臣服心动
臣服心动 2020-12-04 10:40

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

class SomeClass 
{
    required init() {
        // initializer impl         


        
4条回答
  •  天涯浪人
    2020-12-04 11:19

    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"
        }
    }
    

提交回复
热议问题