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

前端之家收集整理的这篇文章主要介绍了ios – Swift – 如何禁止初始化程序?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
考虑以下具有委托的控制器类:

@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”

猜你在找的Xcode相关文章