举个例子:
class A { var num: Int required init(num: Int) { self.num = num } } class B: A { func haveFun() { println("Woo hoo!") } }我已将A 的init 函数标记为required.这到底是什么意思?我在子类 B 中完全省略了它,编译器根本没有抱怨.那怎么需要呢?
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?
推荐答案参见 "自动初始化继承":
规则 1 如果你的子类没有定义任何指定的初始化器,它自动继承其所有超类指定的初始值设定项.
Rule 1 If your subclass doesn’t define any designated initializers, it automatically inherits all of its superclass designated initializers.
规则 2 如果您的子类提供了其所有超类指定的初始值设定项——或者通过继承它们规则 1,或通过提供自定义实现作为其一部分定义——然后它自动继承所有超类便利初始化器.
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.
在您的示例中,子类 B 本身没有定义任何初始化程序,因此它继承 A 的所有初始化器,包括所需的初始化器.如果 B 只定义了便利初始值设定项,同样如此(现已针对 Swift 2 进行更新):
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'如果从 A 的 init 方法中删除 required 然后类 C也可以编译.
If you remove the required from A's init method then class C compiles as well.
更多推荐
“必需"是什么意思?Swift 中的关键字是什么意思?
发布评论