// 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"]
Developer Forum โฉ How do I make (Int,Int) Hashable?
nominal type ๆฏใๆๅๅญ็ๅๅฅใ(typealias ไธ็ฎ nominal type), non-nominal type ๆฏใๆฒๆๅๅญ็ๅๅฅใ๏ผๅฆ๏ผ(Int, Int) tupleใtuples ็ฎๅ็่ตทไพ้ไธๆใ่ชๅใ่ฎๆ Hashableใ
Automatically Synthesized Hashable
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
}
}