Swift iOS macOS 實現 Hasahable 協議
對於一些項目中需要做比較的對象,就需要實現 Hashable
協議,因爲要用到 ==
比如我這裏有個對象 Phrase
,在項目中需要用到 兩個 Phrase
對象作對比,就實現這個 Hashable
protocle
這個協議中主要有兩個方法需要實現:
- static func == (lhs: Object, rhs: Object) -> Bool
- hash(into hasher: inout Hasher)
看官方說明:https://developer.apple.com/documentation/swift/hashable
struct Phrase {
var code: String
var word: String
static func == (lhs: Phrase, rhs: Phrase) -> Bool {
return lhs.code == rhs.code && lhs.word == rhs.word
}
func hash(into hasher: inout Hasher) {
hasher.combine(code)
hasher.combine(word)
}
}