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