Doug Smith Doug Smith - 6 months ago 28
Swift Question

What does the "required" keyword in Swift mean?

Take the following example:

class A {
var num: Int

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

class B: A {
func haveFun() {
println("Woo hoo!")
}
}


I've marked
A
's
init
function as
required
. What exactly does this mean? I completely omitted it in the subclass
B
and the compiler doesn't complain at all. How is it required, then?

Answer

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.

Comments