[英]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.