[英]Type does not conform to an undefined protocol
在Xcode 6 Beta 2中,我编写了以下类:
class Item : Printable, Hashable {
var description:String {
return "..."
}
var hashValue:Int {
return 1
}
}
我收到一条错误,指出类型'Item'不符合协议'Equatable',即使我还没有尝试实现一个名为'Equatable'的协议。 有没有人见过这样的行为? 任何解决方案或解决方法? 谢谢!
根据Hashable
文档:(见该页面的最底部)
符合Hashable协议的类型必须提供名为hashValue的gettable Int属性, 并且还必须提供“is equal”运算符(==)的实现。
根据Equatable
文档,您可以通过为==
定义运算符重载函数来实现这一点,其中您需要的类型位于运算符的每一侧。
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
是你认为会使它们等效的东西。
Hashable
协议实现了Equatable
协议,因此编译器抱怨的原因
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.