Swift 3中使用NSHashTable实现观察者模式
Using NSHashTable to implement Observer pattern in Swift 3
添加多个代理而不是一个代理是一项很常见的任务。假设我们有协议和 class:
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
是 Swift 相当于 Objective C 中的 id
。为了让你的代码编译,你只需要在你的协议中添加 @objc
注释,告诉 Swift 该协议应该与 Objective C.
兼容
所以:
@objc protocol ObserverProtocol {
}
添加多个代理而不是一个代理是一项很常见的任务。假设我们有协议和 class:
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
是 Swift 相当于 Objective C 中的 id
。为了让你的代码编译,你只需要在你的协议中添加 @objc
注释,告诉 Swift 该协议应该与 Objective C.
所以:
@objc protocol ObserverProtocol {
}