Swift - 如何获取从协议(protocol)扩展的类?

标签 swift protocols

有没有一种方法可以获得扩展我的协议(protocol)的 Class 类型或 Struct 类型?

这是我的示例代码:

protocol a {}

extension a {
    static func list(completion: ([StructType] -> Void)) {
        var items = [StructType]()
        ...
        completion(items)
    }
}

struct b{}
extension b: a {}

struct c{}
extension c: a{}

在这种情况下,我想动态获取结构ab 的类型,以便我可以生成它的列表并返回。

预先感谢您友好地回答我的问题。

最佳答案

使用Self关键字

protocol P {
    init()
}

extension P {
    static func list(completion: ([Self]) -> Void) {
        let items = [Self(), Self(), Self()]
        print(Self.self)
        completion(items)
    }
}

struct B {}
extension B: P {}

class C {
    required init() {}
}
extension C: P {}

B.list{ print($0) }
C.list{ print($0) }

关于Swift - 如何获取从协议(protocol)扩展的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42621685/

相关文章:

ios - Swift - 在没有谈话时停止语音识别

communication - 通信协议(protocol)的逆向工程

ios - 如何使用 Swift 在 iOS 中拉伸(stretch)形状( View )?

swift - 在进行 POST 之前等待找到坐标

ios - 如何从输入日期开始计算准确的完成天数

swift - 覆盖协议(protocol)定义变量的 setter 并使用协议(protocol)默认实现中的 getter

swift - 在 Swift 中,如何使用泛型扩展协议(protocol)?

c++ - 如何理解 uart 端口收到了整个消息?

objective-c - 在 Objective-C 中,我是否可以重写父类用来遵守协议(protocol)的子类中的方法?

swift - 通过 NSAppleScript 编写 iTunes 脚本的沙盒权限