As the lead of a Swift contacts app, how would you define equality, hashing and identity for the Contact model across deduplication, caching and diffing?
answer
- one meaning per question
- id-only == hides edits
- name the matching rule
- cache keys must outlive the process
basics
~20 sKeep Contact's == as full value equality, synthesized, and express identity through Identifiable's stable id. Put fuzzy import rules in named keys, key caches by id rather than hashValue or ObjectIdentifier, and ban hand-written == without matching hash(into:).
solid answer
~40 sI separate three questions. **Identity**, which contact is this, is `Identifiable.id`, a stored stable key. **Change**, did anything differ, is `==`, kept as the synthesized full value equality so every edit is visible. **Matching**, are these two imports the same person, is a domain rule, so it gets a named key such as a normalized email and is never folded into `==`. Caches key by `id`: in memory by the `id` value, on disk by a string derived from it, never by `hashValue`, which changes each launch, or `ObjectIdentifier`, which dies with the object. The tradeoff is an id-only `==`: it makes `Set<Contact>` dedupe by entity for free, but breaks the substitutability the `Equatable` documentation asks for and hides edits from anything that compares old and new values.
code
swift · 28 linesimport Foundation
// Full value equality (synthesized) plus a stable identity.
struct Contact: Identifiable, Hashable {
let id: UUID
var firstName: String
var lastName: String
var email: String
}
extension Contact {
// The import rule, named for what it is rather than hidden in ==.
var dedupeKey: String { email.lowercased() }
}
func deduplicated(_ incoming: [Contact]) -> [Contact] {
var seen = Set<String>()
return incoming.filter { seen.insert($0.dedupeKey).inserted }
}
let first = Contact(id: UUID(), firstName: "Ana", lastName: "Lima", email: "[email protected]")
var edited = first
edited.lastName = "Lima-Reis"
print(first.id == edited.id) // true: same contact
print(first == edited) // false: the value changed, so diffing sees an edit
print(deduplicated([first, Contact(id: UUID(), firstName: "Ana", lastName: "Lima",
email: "[email protected]")]).count) // 1go deeper
Recall that an id says which contact it is and == says whether anything changed; they answer different questions.
Explain why synthesized Equatable and Hashable stay paired, and how a Set or Dictionary of ids gives entity lookups without changing ==.
Trace concrete failures back to a mixed-up policy: edits not saved under id-only ==, caches missing after relaunch, imports duplicated by drifting normalization.
Own the policy and its enforcement: three questions, three mechanisms, review rules and contract tests, and weigh convenience at lookup sites against correctness everywhere else.
## The decision A `Contact` model flows through deduplication on import, an avatar cache, list diffing and persistence. Each needs "are these the same?", and each means something different. The lead's job is to decide which Swift mechanism answers which question and to make that rule hold across the codebase, because inconsistent answers produce the hardest bugs in this area: duplicates that come and go, edits that never reach the screen, caches that miss after a relaunch. ## The three questions | Question | Mechanism | Example | |---|---|---| | Which contact is this? | `Identifiable.id`, a stored `UUID` or server key | finding a row to update | | Did anything change? | `==`, synthesized over all stored properties | skipping a redundant save or reload | | Are two imports the same person? | a named matching key, such as `dedupeKey` | merging address books | Keeping them apart is the core of the policy. Each mechanism has its own contract, and folding two questions into one mechanism breaks one of them. ## Option A: `==` compares only `id` Teams reach for this because `Set<Contact>` and `firstIndex(of:)` then work by entity with no extra code. The costs: - **Substitutability breaks.** The `Equatable` documentation says equal instances "can be used interchangeably in any code that depends on their values" and that `==` "should take into account all visible aspects". An edited contact and the original are not interchangeable. - **Edits disappear.** Any code that skips work when the old and new values are `==`, such as a change check before saving or a diff between two arrays, treats a renamed contact as unchanged. - **The rule is invisible.** Readers assume `==` means value equality; a narrower meaning has to be found in the source. Option A is defensible for a reference type whose identity really is the record, but for a struct model it trades a short-term convenience for a long-term class of bugs. ## Option B: value equality plus explicit identity Keep the synthesized `Equatable` and `Hashable`, conform to `Identifiable` with a stored `id`, and look entities up by `id`: - Sets and dictionaries **of ids** (`Set<Contact.ID>`, `[Contact.ID: Contact]`) give entity lookups without touching `==`. - Change detection works for free, because any edited field makes `==` false. - The compiler keeps `==` and `hash(into:)` paired, so the hashing contract cannot drift. The cost is a little ceremony at lookup sites, and synthesized `==` on a large model compares every field, including arrays of phone numbers and addresses, which matters only in hot loops. ## Matching rules belong in named keys "Same email ignoring case" or "same phone after stripping punctuation" are **business rules**, and they change. Expressing one as `var dedupeKey: String` and deduplicating through a `Set<String>` or a dictionary keyed by it keeps it testable, versionable and visible at the call site. Putting it in `==` makes it global and forces `hash(into:)` to normalize identically forever. ## Caching rules - **In memory:** key by `id`. `ObjectIdentifier` is acceptable only for side tables tied to a live class instance, because it is valid only during that instance's lifetime. - **On disk or across processes:** key by a string built from `id`. `hashValue` is seeded per execution and may change between standard-library versions, so it must never be persisted. - **Invalidation:** compare the cached value to the fresh one with `==` to decide whether to rewrite, which is exactly why `==` must see every field. ## Rules to enforce in review 1. Value-type models use synthesized `Equatable` and `Hashable` unless a stored property cannot conform. 2. A hand-written `==` ships with a hand-written `hash(into:)` over the same members, plus a test asserting equal pairs hash equally. 3. Identity is `Identifiable.id`, stored and stable; classes backed by records override the default `ObjectIdentifier` id. 4. Fuzzy matching lives in named keys, never in `==`. 5. No `hashValue` in file names, database columns, user defaults or test fixtures. These rules cost little to adopt and remove whole families of defects, which is the case to make to the team.
- A teammate argues id-only `==` is simpler because `contacts.contains(edited)` just works. How do you answer?It works by quietly changing what `==` means. Every check that compares old and new values, such as a save guard or an array diff, now misses edits. Offer `contacts.contains { $0.id == edited.id }` or a dictionary keyed by `id`: the same convenience, without breaking change detection.
- When would you accept identity-based equality for a model type?For a class whose instances are the identity, such as a live session or a managed record object, where two instances with equal fields are still different things. Then compare with `===` or `id`, document it, and keep such objects out of value-semantics code paths that assume substitutability.
- Making == compare only id is the standard way to dedupe Swift models.
- hashValue is a fine on-disk cache key because it is derived from the fields.
- Identifiable makes Equatable unnecessary for model types.
- ObjectIdentifier is a safe long-lived key for any class instance.
- Fuzzy matching rules belong inside == so every call site agrees.