【问题标题】:How to create Set of Hashable in Swift如何在 Swift 中创建 Hashable 集
【发布时间】:2016-01-12 17:22:47
【问题描述】:

我正在尝试使用以下代码创建Observers 的Set

protocol MyProtocol: Hashable {
    typealias ConcreteType = Self

    var identifier: String { get }
}

extension MyProtocol {
    var hashValue: Int {
        return identifier.hashValue
    }
}

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

protocol Observer: Equatable, Hashable {
    func identifierChanged<T: MyProtocol>(conformant: T)
}

extension Observer {
    func identifierChanged<T: MyProtocol where T == T.ConcreteType>() {} //Optional implementation
}

但是,每当我尝试创建 Set&lt;Observer&gt;(即 let observerSet = Set&lt;Observer&gt;())时,都会收到以下错误:

不支持使用 'Observer' 作为符合协议 'Hashable' 的具体类型

Protocol 'Observer' 只能用作通用约束,因为它具有 Self 或关联的类型要求

有什么办法吗?

【问题讨论】:

    标签: swift generics set swift2 protocols


    【解决方案1】:

    您不能创建处理符合 Swift 协议的对象的集合。如果一个协议在任何地方使用了Self,你就不能再把它当作一个类型,只能作为一个类型约束。在您的情况下,Self 用于Hashable 协议所需的赋值运算符函数。

    在这种情况下,我建议使用类而不是协议。

    有关此问题的更多信息可以在此博客文章和相关文章中找到:http://inessential.com/2015/08/05/swift_diary_9_where_im_stuck

    【讨论】:

    • 我想要几个符合该协议的类,其中一些已经有其他超类,恐怕我现在不能使用类代替协议。
    • 我认为目前唯一的其他解决方案是使用 @objc 协议,但在这种情况下,您不能将其设为 Hashable,您需要使用 NSSet 而不是 Swift Set。跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-07
    • 1970-01-01
    • 1970-01-01
    • 2018-09-04
    • 2021-02-04
    • 2014-07-24
    • 2019-02-24
    相关资源
    最近更新 更多