A Swift contacts importer deduplicates with a Set, yet contacts that compare equal with == survive as duplicates: why, and how do you fix it?
answer
- the hash decides where Set looks
- a hand-written == beside a generated hash
- normalize in both places
- different counts on different runs
basics
~20 sSet picks a slot from the hash before it calls ==, so equal contacts with different hashes usually never get compared. Typical cause: a hand-written == beside a synthesized hash(into:) that hashes every stored property. Hash exactly what == compares.
solid answer
~40 s`Set` and `Dictionary` use the hash to pick a starting bucket and only call `==` on the elements they meet while probing from there. If two contacts are equal by `==` but hash differently, the second insert usually starts somewhere else, misses the first, and is stored as a new element. In Swift the usual cause is a hand-written `==`, say on a lowercased email, while `hash(into:)` is still synthesized and combines every stored property, raw email and display name included. Normalization mismatches do the same thing. The compiler does not warn, and because `Hasher` is seeded per launch the duplicate count changes from run to run. Fix it by writing `hash(into:)` to combine exactly what `==` compares, in the same normalized form, and add a test asserting equal pairs hash equally.
code
swift · 18 linesstruct ImportedContact: Hashable {
var email: String
var displayName: String
// Hand-written: the same contact when the email matches, ignoring case.
static func == (lhs: ImportedContact, rhs: ImportedContact) -> Bool {
lhs.email.lowercased() == rhs.email.lowercased()
}
// No hash(into:) here, so the compiler synthesizes one
// over every stored property, raw email and displayName included.
}
var imported: [ImportedContact] = []
for i in 0..<1_000 {
imported.append(ImportedContact(email: "user\(i)@example.com", displayName: "User \(i)"))
imported.append(ImportedContact(email: "USER\(i)@example.com", displayName: "user \(i)"))
}
print(imported.count, Set(imported).count)go deeper
Remember the one rule behind the bug: values that compare equal with == must produce the same hash, and Set relies on it without checking.
Explain how Set uses the hash to pick a bucket and only then calls ==, and why a hand-written == leaves the synthesized hash(into:) hashing every stored property.
Diagnose from the symptom: duplicates that vary per run point to the hashing contract. Fix both methods from one normalized source and add a hash-equality test so the drift cannot return.
Push domain matching rules such as case-insensitive email out of == into named keys, so value equality stays synthesized and deduplication policy is visible and testable.
## The symptom A contacts app imports address books from several accounts and runs `Set(imported)` to drop duplicates. QA reports that some duplicates survive, the number differs from run to run, and a breakpoint shows `==` returning `true` for the surviving pair. Nothing crashes. The `Set` is behaving as designed; the `Hashable` conformance is broken. ## The contract the standard library relies on `Hashable` inherits from `Equatable`, and the documentation states the requirement plainly: "Two instances that are equal must feed the same values to `Hasher` in `hash(into:)`, in the same order." Put simply, **`a == b` must imply equal hashes**. The reverse is not required: unequal values may collide. Swift does not check this contract at compile time or at run time. It is a semantic promise you make when you write `hash(into:)` or `==` by hand. The compiler cannot check it, because `==` is arbitrary code: it has no way to know which members your comparison reads, or that it lowercases one of them first. Synthesis is the only case where both sides are generated from the same list of stored properties. ## How Set actually looks for an element The standard library's native `Set` lookup works like this: 1. Compute the element's hash with the set's seed and map it to an **ideal bucket**. 2. Walk forward from that bucket through occupied buckets, calling `==` on each element found. 3. Stop at the first match, or at the first empty bucket, which means "not present". If two equal contacts produce different hashes, step 1 sends them to different places. The second contact is compared only with whatever happens to sit on its own probe path, so `==` is never asked about the original and the duplicate goes in. Occasionally the two paths overlap and the duplicate is caught, which is why the count wobbles. Because `Hasher` is seeded per execution, every launch shuffles which pairs happen to meet. ## How Swift code breaks the contract - **A hand-written `==` beside a synthesized `hash(into:)`.** This is the Swift-specific trap. Declaring `Hashable` and writing only `static func ==` leaves `hash(into:)` synthesized over **every stored property**. If `==` compares only the email, two contacts with different display names compare equal but hash differently. The compiler accepts this without a warning. - **Normalization in one place only.** `==` lowercases the email or trims whitespace, while `hash(into:)` combines the raw string. - **Hashing a member that `==` ignores**, such as an import timestamp or a cached avatar. - **A class element whose hashed properties change after insertion.** A `Set` of class instances stores references; mutating a hashed property through another reference leaves the element in a bucket chosen by its old hash. Struct elements are copied into the set, so mutating your own variable afterwards does not affect them. The opposite mistake, hashing **fewer** members than `==` compares, keeps correctness and only costs collisions. ## The fix Pick one definition of "the same contact" and feed it to both requirements: ```swift private var normalizedEmail: String { email.lowercased() } static func == (lhs: ImportedContact, rhs: ImportedContact) -> Bool { lhs.normalizedEmail == rhs.normalizedEmail } func hash(into hasher: inout Hasher) { hasher.combine(normalizedEmail) } ``` Then ask whether this belongs in `==` at all. An import rule such as "same email ignoring case" is narrower than value equality. Moving it into a dedicated key, such as a `Set<String>` of normalized emails or a `Dictionary` keyed by that string, keeps `Contact`'s synthesized `==` and `hash(into:)` intact and makes the rule visible at the call site. ## Making it stay fixed | Check | What it catches | |---|---| | Code review: hand-written `==` without a hand-written `hash(into:)` on a `Hashable` type | the synthesized-hash trap | | A test that builds pairs that should be equal and asserts `a == b` and `a.hashValue == b.hashValue` | normalization drift between the two methods | | A test that the deduplicated `Set` has the expected `count` | the end-to-end symptom | | Preferring synthesized conformances on value types | the whole class of bug, since the compiler pairs the members for you | Run the hash-equality test within one process; it compares two hashes from the same run, so the per-execution seed does not make it flaky.
- Why does the duplicate count change between runs instead of being stable?Whether two mismatched hashes meet depends on which buckets they map to, and `Hasher` is seeded per execution. Each launch shuffles the bucket positions, so a different handful of equal pairs happen to share a probe path and get caught. The wobble is itself a clue that the hashing contract is broken.
- Would you keep the case-insensitive email rule in `==` once it is fixed?Usually not. It is an import rule, not value equality: two contacts with the same email but different names are not interchangeable everywhere. Keep `Contact`'s synthesized conformance and deduplicate through a normalized email key in a `Set<String>` or a `Dictionary`, so the rule is named and cannot drift from `hash(into:)`.
- The model is a class stored in a `Set`. What extra failure can appear?The set holds references. If code mutates a property that `hash(into:)` reads after insertion, the element stays in the bucket chosen by its old hash, so `contains(_:)` can return `false` for an element that is in the set. Hash only immutable members of a class, or keep class instances out of hashed collections keyed by mutable state.
- Set compares every element with == when inserting, so the hash cannot cause duplicates.
- Writing == by hand also makes the compiler synthesize a matching hash(into:).
- The compiler warns when == and hash(into:) use different properties.
- Hashing fewer properties than == compares produces duplicates in a Set.
- Mutating a struct variable after inserting it moves the copy inside the Set.