加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ios – Swift – 如何禁止初始化程序?

发布时间:2020-12-14 17:46:26 所属栏目:百科 来源:网络整理
导读:考虑以下具有委托的控制器类: @objc protocol FooControllerDelegate {}@objc class FooController: UIViewController { var delegate: FooControllerDelegate init(delegate: FooControllerDelegate) { self.delegate = delegate super.init(nibName: nil,
考虑以下具有委托的控制器类:

@objc protocol FooControllerDelegate {
}

@objc class FooController: UIViewController {
    var delegate: FooControllerDelegate

    init(delegate: FooControllerDelegate) {
        self.delegate = delegate
        super.init(nibName: nil,bundle: nil)
    }

    // TODO: How do we forbid this init?
    required init(coder aDecoder: NSCoder) {
        // TODO: Fails to compile.
        super.init(coder: aDecoder) 
    }
}

是否有任何方法禁止使用-initWithCoder:等效,而不会使委托隐式解包,并在方法中放置一个断言(false)?

理想情况下,根本不需要为每个子类编写init(编码器:),并且隐式禁止它.

解决方法

>如果禁止使用除您之外的所有指定初始值设定项的目标,则此时此时没有语言功能.这适用于各种方法.

Overriding method must be accessible as it’s enclosing type

>如果目标是每次添加自定义初始化程序时避免使用init(编码器:)的空覆盖,那么请考虑便捷关键字. Swift的安全范例假定该类要么添加“额外的”init,要么必须修改所有必需的初始化程序的行为.

“Automatic Initializer Inheritance”

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读