Swift iOS macOS 實現 Hasahable 協議

Swift iOS macOS 實現 Hasahable 協議

對於一些項目中需要做比較的對象,就需要實現 Hashable 協議,因爲要用到 ==

比如我這裏有個對象 Phrase,在項目中需要用到 兩個 Phrase 對象作對比,就實現這個 Hashable protocle

這個協議中主要有兩個方法需要實現:

  1. static func == (lhs: Object, rhs: Object) -> Bool
  2. 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)
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章