ios - 具有所需初始化方法的 Swift 类型删除协议(protocol)

标签 ios swift generics protocols

我有符合 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/

相关文章:

ios - Alamofire 无法处理 UDP 请求吗? NSPOSIXErrorDomain 代码=47

Java扩展类类型

java - 如何测试接口(interface) Foo<Bar> 是否是来自 Baz 的 "assignable"?

ios - 我可以从后台线程调用或运行 Core Data Main Context (viewContext) 吗?

objective-c - 用于 iOS ARC 问题的 BWDB SQLite 包装器

ios - 在 ipad 上运行应用程序一次又一次地要求输入系统用户名和密码

iphone - 如何正确使用流对象

swift : Extra Argument in call with scheduledTimerWithTimeInterval

c# - 反射:调用具有泛型参数的方法

swift - 尝试将输出绑定(bind)到 RxSwift 中的 tableviewCell UI 元素