skip to content

In Swift, how should you implement hash(into:) with Hasher, and why must a hashValue never be persisted across launches?

level: middleimportance: should knowfreq 50%

answer

  1. feed components, not a number
  2. the same members == compares
  3. finalize belongs to the caller
  4. seeded at process start

basics

~10 s

Implement hash(into:) by calling hasher.combine(_:) on exactly the members == compares. Hasher is randomly seeded per execution, so hashValue changes between launches and must never be stored in files, databases or caches.

solid answer

~40 s

`Hashable` requires `func hash(into hasher: inout Hasher)`. You call `hasher.combine(_:)` once per essential component, meaning the same members your `==` compares, in a consistent order, and you never call `finalize()` or swap in a different `Hasher`. `hashValue` still exists, but the compiler derives it from `hash(into:)`; implementing it yourself draws a deprecation warning. `Hasher` uses a per-execution seed set at process startup, so the same value hashes differently on the next launch, and the algorithm may change between standard-library versions. A file name, database key or disk cache built from `hashValue` therefore stops matching after a relaunch. Persist a stable key derived from the data itself, such as an ID.

code

swift · 22 lines
swift
struct ContactKey: Hashable {
    var accountID: String
    var contactID: Int

    // The same body the compiler would synthesize, written out.
    func hash(into hasher: inout Hasher) {
        hasher.combine(accountID)
        hasher.combine(contactID)
    }
}

let key = ContactKey(accountID: "work", contactID: 42)
let same = ContactKey(accountID: "work", contactID: 42)

// Within one run, equal values always hash equally.
print(key.hashValue == same.hashValue)        // true

// Changes on the next launch: never a file name or a database key.
print("avatar-\(key.hashValue).png")

// A stable name built from the fields themselves.
print("avatar-\(key.accountID)-\(key.contactID).png")

go deeper

for a junior

Recall the shape: hash(into:) with hasher.combine(_:) for each member that == compares, and never storing a hash value anywhere that outlives the process.

for a middle

Explain why Hasher is seeded per execution, what that does to Set and Dictionary order, and why implementing hashValue now draws a deprecation warning.

for a senior

Spot persisted hash values in review, in cache file names, database keys and test fixtures, and replace them with stable keys derived from the data before they cause silent misses after relaunch.

for a principal

Set the team rule that hash values are process-local, provide a shared stable-key helper for caches and storage, and make the contract test part of every hand-written conformance.

## The requirement is a method, not a number `Hashable` asks for one method: ```swift func hash(into hasher: inout Hasher) ``` A **`Hasher`** is the standard library's universal hash function, the one `Set` and `Dictionary` use. Your job is not to invent an integer. It is to **feed the hasher** the parts of your value that define equality, which the documentation calls its **essential components**: ```swift struct ContactKey: Hashable { var accountID: String var contactID: Int func hash(into hasher: inout Hasher) { hasher.combine(accountID) hasher.combine(contactID) } } ``` This body is what the compiler would synthesize for `ContactKey`, so in practice you write it only when the synthesized version would hash the wrong members. ## Rules for feeding the hasher The `Hashable` and `Hasher` documentation states them directly: - **Combine what `==` compares.** "The components used for hashing must be the same as the components compared in your type's `==` operator implementation." Equal values must feed the same values to `Hasher`, in the same order. - **Call `combine(_:)` per component.** It accepts any `Hashable` value, including arrays, optionals and your own types, which hash themselves recursively. `combine(bytes:)` takes a raw buffer. - **Do not call `finalize()` inside `hash(into:)`**, and do not replace the hasher with a different instance. The documentation warns this "may become a compile-time error in the future"; today it compiles, which is why review has to catch it. - **Do not combine derived or cached members** that `==` ignores, such as a cached thumbnail or a fetch timestamp. ## Where `hashValue` went Before Swift 4.2 you implemented `var hashValue: Int`. Today the compiler provides it from `hash(into:)`, and implementing it as your conformance draws a warning: `'Hashable.hashValue' is deprecated as a protocol requirement; conform type 'AvatarKey' to 'Hashable' by implementing 'hash(into:)' instead`. Reading `hashValue` is still legal. The compiler-provided version runs your `hash(into:)` through a `Hasher` and returns the result, so it is useful for debugging within one run and for nothing else. If a type does implement only `hashValue`, the compiler's `hash(into:)` feeds that number to the hasher, so the hand-written property is still what the type hashes with. ## Why the number changes between launches Swift 4.2 (SE-0206) made hashing **randomly seeded**. The `Hasher()` documentation says it "uses a per-execution seed value that is set during process startup, usually from a high-quality random source". The guarantees, at the strength the standard library states them: | Scope | Guaranteed? | |---|---| | Same bytes fed, same process | the same hash value | | Same value, next launch | not guaranteed; usually different | | Same value, newer standard library | not guaranteed; the algorithm "may itself change" | | Iteration order of a `Set` or `Dictionary` | may differ on each execution | The seed is there to resist **hash flooding**, where crafted inputs pile into the same buckets, and it also flushes out code that relied on a repeatable `Set` order. A typical casualty is a test that compares `Array(selectedIDs)` with an array literal: it passes on one run and fails on the next. Sort the array first, or compare `Set` values with `==`, which ignores order. The practical rule follows from the table: **never persist a hash value.** That includes: 1. File names in an on-disk avatar cache, such as `avatar-\(contact.hashValue).png`. 2. Database columns or `UserDefaults` keys meant to find a record later. 3. Anything sent to a server or another process for comparison. Each works in the run that wrote it and silently misses after a relaunch. A disk cache misses, rebuilds and grows; a persisted lookup returns nothing. ## What to persist instead Build a **stable key from the data itself**: the contact's ID, an account-plus-ID string, or a normalized email. If you need a fixed-width digest, use a named, specified cryptographic or checksum algorithm whose output is defined independently of the process, not `Hasher`. ## Testing and determinism A unit test that asserts a specific `hashValue` will fail on the next run. Assert the contract instead: for pairs of values that compare equal, check that `hashValue` matches within the same run, and check that the `Set` behaves. The standard library has an internal deterministic-hashing mode meant for test environments, and its own comment says it is "not recommended for production use".

  • A unit test asserts that `Contact(id: 7).hashValue` equals a number captured last week. Why does it fail, and what should it check?
    `Hasher` is seeded per execution, so the number differs on each run and may also change with a new standard library. Test the contract instead: for values that compare equal, `hashValue` matches within the same run, and a `Set` built from them has the expected count.
  • Is it legal for `hash(into:)` to combine fewer members than `==` compares?
    It keeps the essential guarantee, because equal values still feed the same inputs, but it raises collisions: values that differ only in the skipped members land in the same buckets. The `Hashable` documentation asks for the same components as `==`, so treat a subset as a deliberate, commented trade, never a shortcut.

A hash value is like a coat-check ticket number: the same coat gets the same number for the rest of tonight, but the numbering starts over next evening, so writing the number in your diary finds nothing tomorrow.

  • hashValue is stable, so it makes a good cache file name.
  • hash(into:) should end by calling hasher.finalize().
  • You conform to Hashable by implementing var hashValue: Int.
  • Set and Dictionary iterate in the same order on every launch.
  • Including a cached timestamp in hash(into:) makes the hash stronger.