Swift中的“必需”关键字是什么意思?

举个例子:
class A {
    var num: Int

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

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

我已经根据需要标记了A的init函数.这是什么意思?我在子类B中完全省略它,编译器根本就不会抱怨.那怎么需要呢?

“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'

如果从A的init方法中删除所需的,那么C类编译也.

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...