如何在 Swift 中将协议作为参数传递 [英] How passing a protocol as parameter in Swift

查看:62
本文介绍了如何在 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.

这篇关于如何在 Swift 中将协议作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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