【问题标题】:Using NSHashTable to implement Observer pattern in Swift 3在 Swift 3 中使用 NSHashTable 实现观察者模式
【发布时间】:2017-06-11 08:45:21
【问题描述】:

添加多个代表而不是只添加一个代表是一项非常常见的任务。假设我们有协议和一个类:

protocol ObserverProtocol
{
   ...
}

class BroadcasterClass
{
    // Error: Type 'ObserverProtocol' does not conform to protocol 'AnyObject'
    private var _observers = NSHashTable<ObserverProtocol>.weakObjects()
}

如果我们试图强制ObserverProtocol 符合AnyObject 协议,我们会得到另一个错误:

不支持使用 'ObserverProtocol' 作为符合协议 'AnyObject' 的具体类型

是否可以在 Swift 3.0 中创建一组弱委托?

【问题讨论】:

    标签: swift delegates swift3 observer-pattern


    【解决方案1】:

    当然,这是可能的。

    AnyObject 是 Objective C 中 id 的 Swift 等价物。要编译你的代码,你只需要在你的协议中添加 @objc 注释,告诉 Swift 协议应该与 Objective 兼容C.

    所以:

    @objc protocol ObserverProtocol {
    
    }
    

    【讨论】:

      猜你喜欢
      • 2011-12-21
      • 1970-01-01
      • 1970-01-01
      • 2017-01-23
      • 1970-01-01
      • 1970-01-01
      • 2013-12-09
      • 1970-01-01
      • 2013-10-28
      相关资源
      最近更新 更多