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

在Swift中按协议查找

发布时间:2020-12-14 05:33:20 所属栏目:百科 来源:网络整理
导读:如何在 Swift中将协议作为参数传递? 在Objective-C中,我可以这样做: id CurrentUserContex userContex = [ServiceLocator locate:@protocol(CurrentUserContex)]; 服务定位器: + (id)locate:(id)objectType 编辑 在Qbyte回答尝试使用后: ServiceLocator.
如何在 Swift中将协议作为参数传递?

在Objective-C中,我可以这样做:

id <CurrentUserContex> userContex = [ServiceLocator locate:@protocol(CurrentUserContex)];

服务定位器:

+ (id)locate:(id)objectType

编辑

在Qbyte回答尝试使用后:

ServiceLocator.locate(CurrentUserContex.self)

但我得到’CurrentUserContex.Protocol’没有确认协议’AnyObject’

所以我尝试过:

ServiceLocator.locate(CurrentUserContex.self as! AnyObject)

但后来我得到:

Could not cast value of type 'ApplicationName.CurrentUserContex.Protocol' (0x7fec15e52348) to 'Swift.AnyObject' (0x7fec15d3d4f8).
如果CurrentUserContex是协议本身的名称,我建议使用它:
ServiceLocator.locate(CurrentUserContex.self)

如果CurrentUserContex是一个类型是协议使用的变量:

ServiceLocator.locate(CurrentUserContex)

我希望这能解决你的问题

(编辑:李大同)

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

    推荐文章
      热点阅读