具有所需init方法的Swift类型擦除协议

时间:2018-05-26 18:41:40

标签: ios swift generics protocols

我的协议符合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
    }
}

毕竟,我们可以像这样使用它     struct TestStruct:TestProtocol {         让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)。 如果AnyTestProtocol包含必需的init方法,我该如何实现TestProtocol

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
    }
}

1 个答案:

答案 0 :(得分:2)

将所需的init(id:)来电转发至T

class AnyTestProtocol<T: TestProtocol>: TestProtocol {

    // ...

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

    // ...
}