添加多个代理而不是仅添加一个委托是一项非常常见的任务.假设我们有协议和类:
protocol ObserverProtocol
{
...
}
class broadcasterClass
{
// Error: Type 'ObserverProtocol' does not conform to protocol 'AnyObject'
private var _observers = NSHashTable<ObserverProtocol>.weakObjects()
}
如果我们试图强制ObserverProtocol符合AnyObject协议,我们将收到另一个错误:
Using ‘ObserverProtocol’ as a concrete type conforming to protocol ‘AnyObject’ is not supported
甚至可以在Swift 3.0中创建一组弱委托吗?
当然,这是可能的.
AnyObject是Objective C中与谓词相同的Swift.为了让您的代码能够编译,您只需要将@objc注释添加到您的协议中,告诉Swift协议应该与Objective C兼容.
所以:
@objc protocol ObserverProtocol {
}