swift - 在 Swift 中按协议(protocol)查找

标签 swift protocols

如何在 Swift 中将协议(protocol)作为参数传递?

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

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

服务定位器:

+ (id)locate:(id)objectType 

编辑

Qbyte 回答后尝试使用:

ServiceLocator.locate(CurrentUserContex.self)

但我收到“CurrentUserContex.Protocol”未确认协议(protocol)“AnyObject”

所以我尝试了:

ServiceLocator.locate(CurrentUserContex.self as! AnyObject)

但后来我得到:

Could not cast value of type 'ApplicationName.CurrentUserContex.Protocol' (0x7fec15e52348) to 'Swift.AnyObject' (0x7fec15d3d4f8).

最佳答案

如果 CurrentUserContex 是协议(protocol)本身的名称,我建议使用它:

ServiceLocator.locate(CurrentUserContex.self)

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

ServiceLocator.locate(CurrentUserContex)

我希望这能解决你的问题

关于swift - 在 Swift 中按协议(protocol)查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31231109/

相关文章:

swift - Realm 对象谓词搜索无效

java.net.ProtocolException : content-length promised 16280 bytes, 但收到 16272

swift - 协议(protocol)中的继承是什么

swift 协议(protocol) : Difference between { get } and { get set } with concrete examples?

Objective-C:如何检查协议(protocol)对象是否是特殊类

Clojure - 将协议(protocol)默认实现与自定义实现混合

ios - 从 ViewController 向 View 传递数据时如何设置委托(delegate)?

swift - EXC_BAD_ACCESS 使用 self.performSelector

ios - 基于 json 的搜索栏过滤器

ios - 如何在swift 3中下载FTP文件