如何在
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)
我希望这能解决你的问题
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。