What does the “required” keyword in Swift mean?

后端 未结 3 1631
暖寄归人
暖寄归人 2020-12-08 20:45

Take the following example:

class A {
    var num: Int

    required init(num: Int) {
        self.num = num
    }
}

class B: A {
    func haveFun() {
              


        
相关标签:
3条回答
  • 2020-12-08 21:03

    “The use of the required modifier ensures that you provide an explicit or inherited implementation of the initializer requirement on all subclasses of the conforming class, such that they also conform to the protocol.”

    Excerpt From: Apple Inc. “The Swift Programming Language (Swift 2).” iBooks. https://itun.es/us/jEUH0.l

    0 讨论(0)
  • 2020-12-08 21:04

    See "Automatic Initializer Inheritance":

    Rule 1 If your subclass doesn’t define any designated initializers, it automatically inherits all of its superclass designated initializers.

    Rule 2 If your subclass provides an implementation of all of its superclass designated initializers—either by inheriting them as per rule 1, or by providing a custom implementation as part of its definition—then it automatically inherits all of the superclass convenience initializers.

    In your example, the subclass B does not define any initializers on its own, therefore it inherits all initializers from A, including the required initializer. The same is true if B defines only convenience initializers (now updated for Swift 2):

    class B: A {
    
        convenience init(str : String) {
            self.init(num: Int(str)!)
        }
    
        func haveFun() {
            print("Woo hoo!")
        }
    }
    

    But if the subclass defines any designated (= non-convenience) initializer then it does not inherit the superclass initializers anymore. In particular the required initializer is not inherited, so this does not compile:

    class C: A {
    
        init(str : String) {
            super.init(num: Int(str)!)
        }
    
        func haveFun() {
            print("Woo hoo!")
        }
    }
    // error: 'required' initializer 'init(num:)' must be provided by subclass of 'A'
    

    If you remove the required from A's init method then class C compiles as well.

    0 讨论(0)
  • 2020-12-08 21:14

    The required keyword means that inheriting classes must provide an implementation of the method. However, the language makes an exception for required initializers:

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

    Reference to the documentation.

    0 讨论(0)
提交回复
热议问题