swift 使用泛型为协议的泛型对象扩展泛型对象

vltsax25  于 2023-04-19  发布在  Swift
关注(0)|答案(1)|浏览(131)

我想在swift中创建一个Array的扩展,其中ObjectWithGenerics的元素如果其泛型符合协议,因此无论我创建什么对象并在数组中拥有什么对象,只要它符合我的协议并且是ObjectWithGenerics类型,我都可以访问扩展中的方法和计算属性。
这就是我所尝试的。

protocol MyProtocol {}

struct ObjectWithGenerics<T> {
    var value: T
}

extension Array where Element == ObjectWithGenerics<MyProtocol> {
    func test() {
        print("It worked")
    }
}

let arr = [Object.ObjectWithGenerics<MyProtocol>]()
// This works but I'm going to be limited to making sure all my arrays are MyProtocols...
arr.test()

struct ConformingObject: MyProtocol {}

// This won't work if I need a specific array of objects like so...
let array = [Object.ObjectWithGenerics<ConformingObject>]()

// This object will not have access to the method `test()` which is the behavior I'm trying to fix
// This object should have access to the `test()` method
array.test()
gopyfrb3

gopyfrb31#

这在Swift中目前是不可能的。请参阅SE-0361的未来方向部分,以了解未来如何实现这一点。
目前,您必须沿着以下方式执行一些操作:

protocol MyProtocol {}

struct ObjectWithGenerics<T> {
    var value: T
}

// Make ObjectWithGenerics implement MyProtocol where appropriate
extension ObjectWithGenerics: MyProtocol where T: MyProtocol {}

// You could also use `extension Collection` here in most cases
extension Array where Element: MyProtocol {
    func test() {
        print("It worked")
    }
}

struct ConformingObject: MyProtocol {}

let array = [ObjectWithGenerics<ConformingObject>]()

array.test()

或者,如果ObjectWithGenerics不能直接符合MyProtocol,您可以使用第二个协议来提升它:

// Create a new protocol for ObjectWithGenerics when the Element is MyProtocol
protocol ObjectWithGenericsElement {}

extension ObjectWithGenerics: ObjectWithGenericsElement where T: MyProtocol {}

extension Array where Element: ObjectWithGenericsElement {
    func test() {
        print("It worked")
    }
}

相关问题