如何在 Swift 中将协议作为参数传递
在 Objective-C 中,我知道如何将 protocol
作为参数传递:
In Objective-C, I know how passing a protocol
as parameter:
- (void)MyMethod:(Protocol *)myparameter
但是在 Swift 中没有更多的 Protocol
类型.
But in Swift there is no more Protocol
type.
如何在不知道哪个是协议的情况下将协议作为参数传递?
How can I pass a protocol as parameter without knowing which is ?
在您的评论之一中,您说:
In one of your comments you say:
我想创建一个方法,该方法返回实现所需协议的类类型数组."
"I want create a method which return an array of type of class which implements a desired protocol."
您是否尝试过以下操作:
Have you tried something like the following:
//notice the use of @objc here
@objc protocol AlertProtocol
{
func getMyName()->String
}
class Class1 : AlertProtocol
{
let name = "Object 1"
func getMyName() -> String
{
return name
}
}
class Class2 : AlertProtocol
{
let name = "Object 2"
func getMyName() -> String
{
return name
}
}
//borrowing from and refactoring siLo's answer
func classesConformingToProtocol(proto:Protocol) -> [AnyClass]
{
let availableClasses : [AnyClass] = [ Class1.self, Class2.self ]
var conformingClasses = Array<AnyClass>()
for myClass : AnyClass in availableClasses
{
if myClass.conforms(to: proto)
{
conformingClasses.append(myClass)
}
}
return conformingClasses
}
然后像这样使用上面的结构:
Then use the above structure like this:
let classes = classesConformingToProtocol(AlertProtocol.self)
完成这项工作的棘手部分是@objc",它将协议暴露给目标 c 运行时,并允许我们将任何协议类型"作为参数传递.
The tricky part that does the work is the "@objc" that exposes the protocol to the objective c runtime and allows us to pass any "Protocol Type" as a parameter.
可能在未来的某个时候,我们将能够以纯粹的"Swift 方式做到这一点.
Probably at some point in the future we will be able to do this in a "pure" Swift way.