Hashable

Swift language Mid-level Swift 5.0+ iOS 17+ Reviewed By Alok Singh

Spot the bug

A Set ends up holding both "Swift" and "swift". Tap the line that breaks the Hashable contract.

  1. struct Tag: Hashable {
  2. let name: String
  3. static func == (lhs: Tag, rhs: Tag) -> Bool {
  4. lhs.name.lowercased() == rhs.name.lowercased()
  5. }
  6. func hash(into hasher: inout Hasher) {
  7. hasher.combine(name)
  8. }
  9. }
Hint 1 of 1

Do equal values produce equal hashes here?

Choose an answer, then open Show answer below to check it.

Show answer
  • Answer: line 7 hasher.combine(name)

Line 7 hashes the original string, but == compares lowercased names. Equal tags then get different hashes. Hash name.lowercased() instead.

30-second answer

Hashable lets a type be used in sets and as dictionary keys. The rule: values that are equal must produce the same hash. Hash exactly the properties that == compares, in the same way. Swift synthesizes both when all stored properties are Hashable, which is usually best.

Practise saying it · 30 s. No recording, just a timer

Explain the Hashable contract.

Say your answer out loud, then check which of these points you covered:

  • Equal values, same hash
  • Hash what == compares
  • Prefer synthesis

Deep dive

Unequal values may share a hash (collisions are allowed).

Hash values are randomly seeded per process, so never persist them.

Changing a hashed property of an object inside a Set breaks the Set.

Identifiable is separate: identity for UI, not hashing.

Common mistakes

  • Comparing case-insensitively in == but hashing the raw string.
  • Saving hashValue to disk.

Senior take & follow-ups

Seniors state the equal-implies-same-hash rule and why mutation inside a Set is dangerous.

Follow-up questions

Think of your answer first, then open the hint.

  1. Why are hash seeds random?

    Show hint

    To resist hash-flooding attacks.

  2. What happens if equal values hash differently?

    Show hint

    Sets and dictionaries can hold duplicates and fail lookups.

Suggest a fix if something here is wrong or out of date.