๐Ÿ…ฟ๏ธHashable

// can't use tuple as key
let tuple = ("I want to be part of a key", "Me too!")

// โ›” error: 
//       generic struct 'Dictionary' requires that 
//       '(String, String)' conform to 'Hashable'
let dict = [tuple: "I am a value"]

// โœ… fix (automatically synthesized Hashable)
struct Pair<T: Hashable, U: Hashable>: Hashable {
    let left: T
    let right: U
    // convenience init
    init(_ left: T, _ right: U){
        self.left = left
        self.right = right
    }
}

let pair = Pair("Joe", 20)      // โญ๏ธ ไฝฟ็”จ Pair ๆ™‚๏ผŒไธ้œ€็‰นๅˆฅๆŒ‡ๅฎš <T, U>
let dict = [pair: "friend"]

Automatically Synthesized Hashable

  • Declare Hashable conformance in the typeโ€™s original declaration.

  • For a struct, all its stored properties must conform to Hashable.

  • For an enum, all its associated values must conform to Hashable.

  • An enum without associated values has Hashable conformance even without the declaration.

Implementing Hashable Manually

struct Pair<T: Hashable, U: Hashable>: Hashable {
    // properties ...
    // init ...
    
    // โญ๏ธ Hashable requirement
    hash(into hasher: inout Hasher){
        hasher.combine(left)
        hasher.combine(right)
    }
    
    // โญ๏ธ Equatable requirement
    static func == (p1: Pair<T,U>, p2: Pair<T,U>) -> Bool {
        return p1.left == p2.left && p1.right == p2.right
    }
}

Last updated