举个例子:
class A { var num: Int required init(num: Int) { self.num = num } } class B: A { func haveFun() { println("Woo hoo!") } }
见
“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.
在你的例子中,B子类没有自己定义任何初始化器,因此它是
从A继承所有初始化器,包括所需的初始化程序.
如果B仅定义方便的初始化器,则也是如此
(现已更新为Swift 2):
class B: A { convenience init(str : String) { self.init(num: Int(str)!) } func haveFun() { print("Woo hoo!") } }
但是如果子类定义了任何指定的(=非便利)初始化器,那么它就可以了
不再继承超类初始化器了.特别是所需的
初始化程序不是继承的,所以这不编译:
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'