0Pricing
Swift Academy · Lesson

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))  // true

All lessons in this course

  1. Synthesized Equatable
  2. Hashable and hash(into:)
  3. Comparable and Sorting
  4. Custom Equality Semantics
← Back to Swift Academy