Swift iOS macOS 实现 Hashable 协议
对于一些项目中需要做比较的对象,就需要实现 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)
}
}