Swift - 如何获得从协议扩展的类?

Nor*_*rak 7 protocols swift

有没有办法获得扩展我的协议的类类型或结构类型?

这是我的示例代码:

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{}
Run Code Online (Sandbox Code Playgroud)

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

预先感谢您亲切地回答我的问题。

Ale*_*ica 5

使用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) }
Run Code Online (Sandbox Code Playgroud)