In Swift, how do ==, ===, ObjectIdentifier and Identifiable's id differ when deciding whether two contacts are the same?
answer
- value, instance, handle, entity
- triple equals takes AnyObject?
- valid only while the object lives
- Identifiable does not imply Equatable
basics
~20 s== asks whether two values are equal under Equatable; === asks whether two class references point to the same instance; ObjectIdentifier makes that instance identity Hashable; Identifiable's id names a stable entity that survives edits.
solid answer
~40 s`==` is `Equatable` value equality: whatever the type's author defined, usually every stored property. `===` takes `AnyObject?` operands, so it only applies to class instances and asks whether two references point to the same object; for a struct the compiler rejects it. `ObjectIdentifier(object)` wraps that instance identity in a `Hashable` value, handy as a dictionary key, but the standard library says it is valid for comparisons only during the instance's lifetime. `Identifiable` requires an `id` of a `Hashable` type naming the entity, so an edited contact keeps its `id` while `==` turns false. `Identifiable` does not make a type `Equatable`. For classes the default `id` is `ObjectIdentifier(self)`, which is unique only while the object lives.
code
swift · 21 linesimport Foundation
struct Contact: Identifiable { // a value: identity is a stored id
let id: UUID
var displayName: String
}
final class SyncSession: Identifiable {} // a class: default id is ObjectIdentifier(self)
let original = Contact(id: UUID(), displayName: "Ana Lima")
var renamed = original
renamed.displayName = "Ana L."
print(original.id == renamed.id) // true: same contact
// print(original == renamed) // error: Contact is not Equatable
// print(original === renamed) // error: === needs class instances
let s1 = SyncSession()
let s2 = s1
let s3 = SyncSession()
print(s1 === s2, s1 === s3) // true false
print(s1.id == ObjectIdentifier(s2)) // truego deeper
Recall the split: == compares values, === compares class references, and Identifiable's id names which entity a value represents.
Explain why === only compiles for class instances, why ObjectIdentifier is Hashable but lifetime-bound, and why Identifiable gives no == of its own.
Catch the production bugs: caches keyed by ObjectIdentifier outliving their objects, classes keeping the default id for database records, and == redefined as id equality hiding edits.
Define, per model type, which notion answers which question, entity identity for lookups and value equality for change detection, and write it into the type's documentation.
## Four different questions "Are these two contacts the same?" hides four questions, and Swift gives each its own tool: | Tool | Question it answers | Works on | Defined by | |---|---|---|---| | `==` | do these two values have equal contents? | any `Equatable` type | the type's author, or synthesis | | `===` / `!==` | do these references point to one instance? | class and actor instances | the runtime | | `ObjectIdentifier` | a `Hashable` handle for one instance or metatype | classes, actors, metatypes | the runtime | | `Identifiable.id` | which real-world entity is this? | any type that conforms | the type's author | ## `==`: value equality `==` is the one requirement of `Equatable`. For a synthesized conformance it compares every stored property. The standard library describes equality as **substitutability**: "any two instances that compare equally can be used interchangeably in any code that depends on their values". It also states that "the identity of a class instance is not part of an instance's value". That is why a class's hand-written `==` normally compares contents, and two distinct objects can still be `==`. ## `===`: instance identity `===` is declared as `func === (lhs: AnyObject?, rhs: AnyObject?) -> Bool`. Consequences: - It compiles only for class instances or class-constrained types. For a struct the compiler reports `argument type 'Contact' expected to be an instance of a class or class-constrained type`. - Two `nil` references are identical; one `nil` and one object are not. - For non-`nil` operands the standard library implements it as `ObjectIdentifier(l) == ObjectIdentifier(r)`. Structs and enums have **no identity** to compare. The `ObjectIdentifier` documentation is explicit that only class instances, actor instances and metatypes have unique identities in Swift. ## `ObjectIdentifier`: identity you can hash `ObjectIdentifier` is `Hashable`, which makes it the standard key when you need a per-instance side table, such as an avatar loader keyed by the sync session object that requested it. The catch is in its documentation: the identifier "is valid for comparisons only during the lifetime of the instance". After an object is deallocated, a new object can reuse the address, and a stale key then matches the wrong instance. Use it only while you also keep the object alive, or clear the entry when the object goes away. It also identifies **metatypes**: `ObjectIdentifier(Contact.self)` is a common key for registries keyed by type, and that use avoids the lifetime problem, because metatypes are not freed and reused the way class instances are. ## `Identifiable`: stable entity identity `Identifiable` (standard library, Swift 5.1) has one requirement, `var id: ID { get }`, with `ID: Hashable`. It answers "which contact is this?" across edits: - A renamed contact keeps its `id` while `==` becomes `false`, which is exactly the distinction diffing code needs. - **`Identifiable` does not imply `Equatable`.** A `Contact: Identifiable` without `Equatable` cannot use `==`; the compiler reports `binary operator '==' cannot be applied to two 'Contact' operands`. - **Classes get a default `id`** of `ObjectIdentifier(self)`. The documentation warns this "is only guaranteed to remain unique for the lifetime of an object", so a class backed by a database record should supply the record's key instead. - **Value types must supply `id`** themselves, usually a stored `UUID` or a server ID. The protocol deliberately leaves the scope of identity to the conformer. The documentation lists options from "always unique, like UUIDs" through "unique within the current collection, like collection indices", and says both sides should document which one applies. Frameworks that track collection elements across updates read `id`; SwiftUI's use of it is covered with SwiftUI view identity. ## Choosing in a contacts app 1. **Contact as a struct:** `Identifiable` with a stored `id`, plus synthesized `Hashable`. Use `id` for "same contact" and `==` for "nothing changed". 2. **A class such as a sync session:** compare with `===` when the question is "same session object", and key per-instance caches by `ObjectIdentifier` only while the session is alive. 3. **Do not redefine `==` as `id` equality** just to make lookups convenient. It makes every edit invisible to code that skips work when old and new values are `==`.
- Why is `ObjectIdentifier` a risky key for an on-disk or long-lived cache?It is valid for comparisons only while the instance lives. Once the object is deallocated, a new object can receive the same identifier, so a stale entry can match an unrelated instance. Use it for in-memory side tables tied to the object's lifetime, and key anything longer-lived by a stable domain ID.
- A class conforms to `Identifiable` and stores a database record. Should it keep the default `id`?Usually not. The default is `ObjectIdentifier(self)`, unique only for the object's lifetime, so two objects loaded for the same record get different ids. Declare `id` as the record's key, so identity follows the data rather than the allocation.
- === compares two structs field by field.
- Conforming to Identifiable makes == compare the id.
- ObjectIdentifier stays unique even after the object is deallocated.
- Two distinct class instances can never be == to each other.
- A class's default Identifiable id survives reloading the same record.