在 Swift 中按协议查找 [英] Find by Protocol in Swift

查看:46
本文介绍了在 Swift 中按协议查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I pass a protocol as a parameter in Swift?

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

In Objective-C I could do this:

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

服务定位器:

+ (id)locate:(id)objectType 

编辑

Qbyte 回答后尝试使用:

After Qbyte answer tried using:

ServiceLocator.locate(CurrentUserContex.self)

但我得到CurrentUserContex.Protocol"不确认协议AnyObject"

But I'm getting 'CurrentUserContex.Protocol' does not confirm to protocol 'AnyObject'

所以我尝试了:

ServiceLocator.locate(CurrentUserContex.self as! AnyObject)

但后来我得到:

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

推荐答案

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

I would suggest to use this if CurrentUserContex is the name of the protocol itself:

ServiceLocator.locate(CurrentUserContex.self)

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

If CurrentUserContex is a variable which type is a protocol use:

ServiceLocator.locate(CurrentUserContex)

希望这能解决您的问题

这篇关于在 Swift 中按协议查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆