如何在Swift中创建哈希表集

如何在Swift中创建哈希表集,swift,generics,set,swift2,protocols,Swift,Generics,Set,Swift2,Protocols,我正在尝试使用以下代码创建观察者的集合: protocol MyProtocol: Hashable { typealias ConcreteType = Self var identifier: String { get } } extension MyProtocol { var hashValue: Int { return identifier.hashValue } } func ==<T: MyProtocol>(lh

我正在尝试使用以下代码创建
观察者的
集合

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
}
协议MyProtocol:可哈希{
typealias ConcreteType=Self
变量标识符:字符串{get}
}
扩展MyProtocol{
var hashValue:Int{
返回标识符.hashValue
}
}
func==(左:T,右:T)->Bool{
返回lhs.identifier==rhs.identifier
}
协议观察者:可均衡、可散列{
功能标识已更改(符合:T)
}
扩展观测器{
func identifierChanged(){}//可选实现
}
但是,每当我尝试创建
集时(即
让observerSet=Set()
),就会出现以下错误:

不支持将“Observer”用作符合协议“Hashable”的具体类型

协议“Observer”只能用作一般约束,因为它具有自身或关联的类型要求


有什么办法吗?

您不能创建一个集合来处理符合Swift协议的对象。如果协议在任何位置使用
Self
,则不能再将其用作类型,而只能用作类型约束。在您的情况下,
Self
用于分配运算符函数,该函数是
Hashable
协议所要求的

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


关于这个问题的更多信息可以在这篇博文和相关文章中找到:

我希望有几个类符合这个协议,其中一些已经有了其他的超类,恐怕我现在不能用类来代替协议。我认为目前唯一的解决方案是使用@objc协议,但在这种情况下,您不能使其可散列,您需要使用NSSet而不是Swift集。