Equatable and Hashable — why? Why must a Dictionary key be Hashable?
The idea
Equatable provides the == operator — "these two values are the same". Hashable refines Equatable and adds hash(into:) — folding the value into a number via Hasher. Dictionary and Set require Hashable from the key/element because they search by hash rather than by scanning: hash → bucket index, then == to resolve collisions. This gives O(1) on average (worst case, with massive collisions, O(n)).
struct User: Hashable { // == and hash(into:) synthesized from all fields
let id: Int
let name: String
}
struct Tag: Hashable { // custom semantics: case-insensitive
let value: String
static func == (l: Tag, r: Tag) -> Bool {
l.value.lowercased() == r.value.lowercased()
}
func hash(into hasher: inout Hasher) {
hasher.combine(value.lowercased()) // equal → equal hash
}
}
let tags: Set<Tag> = [Tag(value: "Swift"), Tag(value: "swift")]
print(tags.count) // 1
var ages: [User: Int] = [:]
ages[User(id: 1, name: "Ann")] = 30
The rest of this answer, with code and interview follow-ups, is in the DevPrep app.
Read the full answer in DevPrep