加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

使用NSHashTable在Swift 3中实现Observer模式

发布时间:2020-12-14 05:40:43 所属栏目:百科 来源:网络整理
导读:添加多个代理而不是仅添加一个委托是一项非常常见的任务.假设我们有协议和类: protocol ObserverProtocol{ ...}class BroadcasterClass{ // Error: Type 'ObserverProtocol' does not conform to protocol 'AnyObject' private var _observers = NSHashTabl
添加多个代理而不是仅添加一个委托是一项非常常见的任务.假设我们有协议和类:
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 {

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读