[英]Swift - How to forbid an initializer?
Consider the following controller class with a delegate:考虑以下带有委托的控制器类:
@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)
}
}
Is there any way to forbid the usage of the -initWithCoder:
equivalent, without making the delegate implicitly unwrapped, and placing an assert(false)
inside the method?有什么方法可以禁止使用-initWithCoder:
等效项,而不使委托隐式展开,并在方法中放置一个assert(false)
?
Ideally, it won't be necessary to write the init(coder:)
with each subclass at all, and have it implicitly forbidden.理想情况下,根本没有必要为每个子类编写init(coder:)
并隐式禁止它。
Overriding method must be accessible as it's enclosing type覆盖方法必须可访问,因为它是封闭类型
init(coder:)
each time you adding custom initialiser then think about convenience
keyword.如果目标是避免每次添加自定义初始化程序时对init(coder:)
空覆盖,那么请考虑convenience
关键字。 Swift's safety paradigm assumes that class either adds 'additional' init or has to modify behaviour of all required initialisers. Swift 的安全范式假设该类要么添加“额外的”init,要么必须修改所有必需初始化器的行为。Have you tried using @available
attribute like mentioned here ?您是否尝试过使用此处提到的@available
属性?
Luckily, you can use Swift's @available attribute to prevent this, which also has the benefit of more clearly communicating that you should not use this initializer.幸运的是,您可以使用 Swift 的 @available 属性来防止这种情况发生,这也有利于更清楚地传达您不应使用此初始化程序。
The solution seems to work pretty well:该解决方案似乎工作得很好:
@available(*, unavailable)
public required init?(coder: NSCoder) {
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.