Custom Equality Semantics
Implement domain-correct equality rules.
When Default == Is Wrong
Synthesized == compares every stored property. Sometimes that is too strict (you only care about an id) or too loose. Then you write == yourself.
Identity-Based Equality
Treat two records as equal when their ids match, ignoring other fields:
struct Account: Equatable {
let id: Int
var balance: Int
static func == (l: Account, r: Account) -> Bool { l.id == r.id }
}
print(Account(id: 1, balance: 10) == Account(id: 1, balance: 999)) // trueAll lessons in this course
- Synthesized Equatable
- Hashable and hash(into:)
- Comparable and Sorting
- Custom Equality Semantics