在Swift中按协议查找

在Swift中按协议查找,swift,protocols,Swift,Protocols,如何在Swift中将协议作为参数传递 在Objective-C中,我可以这样做: id <CurrentUserContex> userContex = [ServiceLocator locate:@protocol(CurrentUserContex)]; 编辑 Qbyte回答后,尝试使用: ServiceLocator.locate(CurrentUserContex.self) 但我得到的“CurrentUserContex.Protocol”与协议“AnyObject”

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

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

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

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)

我希望这能解决您的问题

在Swift中,您必须传递一个类所有类都符合AnyObject协议。所以CurrentUserContex也必须是一个类,您可以使用.self或不使用.self进行尝试。不幸的是,我没有足够的参考来告诉您确切使用哪个类。

试试看

ServiceLocator.locate(CurrentUserContex.self as Protocol)
或者在某些版本中,由于某些原因,错误协议未被识别为任何对象:

ServiceLocator.locate((CurrentUserContex.self as Protocol) as! AnyObject)
协议作为方法参数: 这里还有一些其他选择:


可能重复为什么要将协议作为类型本身传递?您可能会发现这个答案很有用:对于工作实现,提供了两种类型,一种是基本的,另一种是延迟初始化的。感谢您的快速响应,尝试使用您的答案时出现此错误:无法将“ApplicationName.CurrentUserContex.Protocol”0x7fec15e52348类型的值强制转换为“Swift.AnyObject”,尝试此操作时:ServiceLocator.locateCurrentUserContex.self!anyobject您尝试使用的方法是什么?我找不到任何参考资料。ServiceLocator来自哪里?类型、模块、框架是我为依赖注入框架创建的包装。在Typhone中,该方法的名称是componentForTypeOk,因此我最终使用了它,并将服务定位器方法更改为+idlocate:protocol*protocolType。谢谢,这很酷,但是您能限制协议类型吗?在swift和objc中断言类型有点棘手。您可以尝试上面的源链接中的一些建议。也许NSStringFromProtocol会派上用场。让我知道你的想法,因为互联网上关于这个话题的信息很少。我最终决定,我可以接受任何对象。我只想接受类协议,所以这就足够了。我能够使它只在协议中工作,但这要求协议必须是@objc,这是我不想要的。我在探索Swift的可能性,而不是如何将Objective-C运行时插入Swift代码。你可以看看这个问题:看看我在尝试做什么。
ServiceLocator.locate((CurrentUserContex.self as Protocol) as! AnyObject)
protocol Describable:class{var text:String{get}}
class A:Describable{var text:String;init(_ text:String){self.text = text}}
class B:A{}
class C{}


let a = A("I am a")
let b = B("I am b")
let c = C()

func ofType<T>(instance:Any?,_ type:T.Type) -> T?{/*<--we use the ? char so that it can also return a nil*/
    if(instance as? T != nil){return instance as? T}
    return nil
}

Swift.print(ofType(a,A.self)!.text)//I am a
Swift.print(ofType(a,Describable.self)!.text)//I am a
Swift.print(ofType(b,B.self)!.text)//I am b
Swift.print(ofType(c,C.self))//instance of c