Swift类型的擦除协议以及所需的init方法

弗拉迪斯拉夫

我有符合的协议 Equatable

protocol TestProtocol: Equatable {
    var id: Int {get}
}

func ==<T: TestProtocol>(lhs: T, rhs: T) -> Bool {
    return lhs.id == rhs.id
}

为了有机会存储TestProtocol值,我们应该使用类型擦除。

class AnyTestProtocol<T: TestProtocol>: TestProtocol {
    var id: Int {
        return item.id
    }

    private let item: T

    init(_ testProtocol: T) {
        self.item = testProtocol
    }
}

而且,毕竟,我们可以使用它,就像这样的结构TestStruct:TestProtocol {let id:Int}

let a = TestStruct(id: 1)
let b = TestStruct(id: 1)

a == b /// true

// let a = TestStruct(id: 1)
// let b = TestStruct(id: 0)
// a == b /// false

一切都好。但是我想TestProtocol与所需的init方法一起使用,例如init(id: Int)如何实现AnyTestProtocolIfTestProtocol包含必需的init方法?

protocol TestProtocol: Equatable {
    var id: Int {get}

    /// Required init method for every protocol implementation
    init(id: Int)
}

func ==<T: TestProtocol>(lhs: T, rhs: T) -> Bool {
    return lhs.id == rhs.id
}

class AnyTestProtocol<T: TestProtocol>: TestProtocol {
    var id: Int {
        return item.id
    }

    private let item: T

    required init(id: Int) {
        ????????
    }

    init(_ testProtocol: T) {
        self.item = testProtocol
    }
}
马丁·R

只需将所需的init(id:)呼叫转发T

class AnyTestProtocol<T: TestProtocol>: TestProtocol {

    // ...

    required init(id: Int) {
        self.item = T(id: id)
    }

    // ...
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章