我有符合 Equatable
的协议(protocol)
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
}
}
而且,毕竟我们可以像这样使用它 结构测试结构:测试协议(protocol){ 让 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)
。
如果 TestProtocol
包含所需的初始化方法,我该如何实现 AnyTestProtocol
?
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
}
}
最佳答案
只需将所需的 init(id:)
调用转发给 T
:
class AnyTestProtocol<T: TestProtocol>: TestProtocol {
// ...
required init(id: Int) {
self.item = T(id: id)
}
// ...
}
关于ios - 具有所需初始化方法的 Swift 类型删除协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50545964/