在 Xcode 6 Beta 2 中,我编写了以下类:
class Item : Printable, Hashable {
var description:String {
return "..."
}
var hashValue:Int {
return 1
}
}
我收到一条错误消息,指出类型“Item”不符合协议(protocol)“Equatable”,即使我没有尝试实现名为“Equatable”的协议(protocol)。有没有人见过这样的行为?任何解决方案或解决方法?谢谢!
最佳答案
根据 the Hashable
docs: (请参阅该页面的最底部)
Types that conform to the Hashable protocol must provide a gettable Int property called hashValue, and must also provide an implementation of the “is equal” operator (==).
并根据the Equatable
docs为此,您可以为 ==
定义一个运算符重载函数,其中您想要的类型位于运算符的每一侧。
func == (lhs: MyStruct, rhs: MyStruct) -> Bool {
return lhs.name == rhs.name
}
这意味着你的代码是这样的:
class Item : Printable, Hashable {
var description:String {
return "..."
}
var hashValue:Int {
return 1
}
}
func == (lhs: Item, rhs: Item) -> Bool {
return lhs.hashValue == rhs.hashValue
}
// Testing...
Item() == Item() //-> true
当然,假设 hashValue
是您认为会使它们等价的值。
关于ios - 类型不符合未定义的协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24661096/