我想在我的类中嵌套一个协议(protocol)来实现委托(delegate)模式,如下所示:
class MyViewController : UIViewController {
protocol Delegate {
func eventHappened()
}
var delegate:MyViewController.Delegate?
private func myFunc() {
delegate?.eventHappened()
}
}
但是编译器不允许:
Protocol 'Delegate' cannot be nested inside another declaration
我可以通过在类范围之外声明 MyViewControllerDelegate
来轻松地使其工作。
我的问题是为什么这样的限制?
最佳答案
Swift enables you to define nested types, whereby you nest supporting enumerations, classes, and structures within the definition of the type they support.
鉴于协议(protocol)不在该列表中,目前似乎不支持它。 他们有可能在某个时候添加该功能(毕竟 Swift 发布不到 2 年)。关于他们为什么不会或没有的任何想法都是我的猜测。
关于Swift 协议(protocol)嵌套在一个类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36066548/