在Swift中按协议查找

如何在 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)

我希望这能解决你的问题

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...