数组扩展,其中元素是Swift中的通用结构

Ant*_*ito 2 generics swift

如何扩展具有通用类型的结构数组?请查看以下代码以了解我要执行的操作。

struct MyStruct<T: MyProtocol> {
   ...
}

extension Array where Element: MyStruct<T> { // Not sure if T is supposed to be on this line.

    func doWork() -> [T] {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

基本上,我将如何编写扩展以使方法返回传递给该结构的泛型类型的数组。

Dam*_*aux 6

您将需要创建具有关联类型的协议:

protocol MyGenericStructProtocol {
    associatedtype GenericType
}
Run Code Online (Sandbox Code Playgroud)

让您的结构直接或通过扩展采用协议:

extension MyStruct: MyGenericStructProtocol {
    typealias GenericType = T
}
Run Code Online (Sandbox Code Playgroud)

现在,您可以在Array扩展内引用泛型类型:

extension Array where Element: MyGenericStructProtocol {
    func doWork() -> [Element.GenericType] {
        return []
    }
}
Run Code Online (Sandbox Code Playgroud)

此GitHub要点上查看完整的示例