skip to content

Equality, Hashing and Ordering

Equatable, Hashable and Comparable define equality, hashing and order, often synthesized by the compiler. Interviewers ask about the hash contract and identity versus equality.

on this pageshow

explore

questions

6

In Swift, when does the compiler synthesize Equatable and Hashable for your own type, and when must you write them yourself?

level: juniorimportance: must knowfreq 72%

answer

  1. you have to ask for it
  2. every stored property must conform
  3. payload-free enums need no declaration
  4. same file as the type
  5. classes are left out

basics

~20 s

Swift synthesizes == and hash(into:) when you declare Equatable or Hashable in the type's own file and every stored property (struct) or associated value (enum) conforms. Classes never get it; enums without payloads conform even undeclared.

solid answer

~40 s

Synthesis is opt-in: you declare `Equatable` or `Hashable` on the type, in its declaration or an extension in the same file, and write no `==` or `hash(into:)`. For a struct every stored property must conform; for an enum every associated value must. An enum with no associated values is `Equatable` and `Hashable` without declaring anything. Classes never get synthesis, so you write `==` (and `hash(into:)`) yourself. The synthesized `==` compares all stored properties and the synthesized `hash(into:)` feeds all of them to the `Hasher`, so you hand-write them only when equality should mean something narrower, such as ignoring a cache field. `Comparable` is synthesized only for enums without raw values, ordered by case declaration (Swift 5.3).

code

swift · 22 lines
swift
struct PhoneNumber: Hashable {
    var digits: String
}

struct Contact: Hashable {      // synthesized: every stored property is Hashable
    var firstName: String
    var lastName: String
    var phones: [PhoneNumber]   // Array is Hashable because PhoneNumber is
    var nickname: String?       // Optional is Hashable because String is
}

enum Label { case home, work, mobile }  // no payloads: Equatable and Hashable undeclared

enum Priority: Comparable { case low, normal, high }  // synthesized <, by case order

let a = Contact(firstName: "Ana", lastName: "Lima",
                phones: [PhoneNumber(digits: "5550100")], nickname: nil)
var b = a
print(a == b, Set([a, b]).count)   // true 1
b.nickname = "Ani"
print(a == b)                      // false
print(Set([Label.home, .home]).count, Priority.low < .high)  // 1 true

go deeper

for a junior

Recall the trigger: declare the protocol, write nothing, and every stored property or associated value must conform. Know that payload-free enums conform without a declaration and that classes never get synthesis.

for a middle

Explain what the generated == and hash(into:) actually touch, why the same-file rule exists, and how a generic member such as an array or optional passes conformance through.

for a senior

Show the production trap: a hand-written == beside a still-synthesized hash(into:) silently breaks Set and Dictionary. Read the compiler's notes to find the blocking member quickly.

for a principal

Decide where synthesized equality is the team default and when a type earns a hand-written conformance, and require that hand-written == and hash(into:) always change together under review.

## Synthesis is something you opt into Swift does not make every type comparable by default. A struct called `Contact` with two `String` properties cannot be used with `==` until you **declare** the conformance: ```swift struct Contact: Hashable { var firstName: String var lastName: String } ``` When you declare `Equatable` or `Hashable` and write none of the requirements yourself, the compiler **synthesizes** them: it writes `static func ==` and `func hash(into:)` for you. This arrived with Swift 4.1 (SE-0185), and since Swift 4.2 the synthesized `Hashable` writes `hash(into:)` rather than the old `hashValue` property. The declaration must sit in the type's original declaration or in an **extension in the same file**. The rule exists so that the generated code can read `private` and `fileprivate` stored properties. An extension in another file is refused with the compiler error `extension outside of file declaring struct 'Contact' prevents automatic synthesis of '==' for protocol 'Equatable'`. ## Which types qualify | Kind of type | `Equatable` / `Hashable` synthesized when | `Comparable` synthesized? | |---|---|---| | `struct` | every stored property conforms | never ("not supported for struct declarations") | | `enum` with associated values | every associated value conforms | yes, if every associated value is `Comparable` and there is no raw type | | `enum` without associated values | always, even with no declaration | yes, if declared and there is no raw type | | `class` | never | never | Two details trip people up: - **Conformance is recursive through generic types.** `[PhoneNumber]` is `Hashable` only because `PhoneNumber` is, and `String?` is `Hashable` because `String` is. One non-conforming member anywhere in the chain blocks the whole type. - **Only stored properties count.** Computed properties and `static` properties are not compared or hashed, because they are not part of the value's storage. ## What the generated code does The synthesized `==` compares **every stored property** of a struct, or the case and then every associated value of an enum. The synthesized `hash(into:)` calls `hasher.combine(_:)` with the same members. That pairing is what keeps the generated code safe: equal values always feed the same inputs to the `Hasher`. For enums, `Comparable` synthesis (Swift 5.3, SE-0266) orders values by **case declaration order**, then by associated values. Reordering the cases therefore changes how a sorted array of them comes out. An enum with a raw type is excluded; the compiler says `enum declares raw type 'String', preventing synthesized conformance of 'Tag' to 'Comparable'`. ## When the compiler refuses A refusal is a compile error, not a silent fallback: - A stored property whose type does not conform. The note names it: `stored property type 'AvatarImage' does not conform to protocol 'Equatable', preventing synthesized conformance of 'ContactCard' to 'Equatable'`. - The conformance is declared in an extension in another file. - The type is a class. The error is the plain `type 'Group' does not conform to protocol 'Equatable'`; nothing is generated for classes, `final` or not, because a class's equality has to account for superclass state and subclass overriding. - `Comparable` declared on a struct: `automatic synthesis of 'Comparable' is not supported for struct declarations`. Common blockers in app models are closure properties (function types never conform), `Any` or an existential without a `Hashable` requirement, and a framework type that is not `Equatable`. ## When to write it yourself You write the requirements by hand when: 1. **The type is a class.** You decide what equality means, usually by comparing the values that define it. 2. **A member cannot conform**, such as a stored closure. You compare the members that matter and leave the closure out. 3. **Equality should be narrower than all stored properties**, for example ignoring a cached thumbnail or a last-fetched timestamp. In the third case the rule is strict: if you hand-write `==`, hand-write `hash(into:)` too, combining exactly the members `==` compares. If you write only `==` and keep `Hashable` declared, the compiler still synthesizes `hash(into:)` over **all** stored properties, and two values that compare equal can hash differently. ## Release notes - Swift 4.1: synthesized `Equatable` and `Hashable` for structs and enums (SE-0185). - Swift 5.3: synthesized `Comparable` for enums without raw values (SE-0266). - Swift 6.4: `Equatable`, `Hashable` and `Comparable` admit noncopyable types (SE-0499), so a `~Copyable` struct can declare `Equatable` and receive a synthesized `==`. It still cannot be a `Set` element, because `Set` requires copyable elements.

  • Your struct has a stored closure property. How do you still make it Equatable?
    Function types never conform to `Equatable`, so synthesis is refused. Write `static func ==` yourself and compare the properties that define the value, leaving the closure out. If the type is also `Hashable`, write `hash(into:)` to combine exactly those same properties, or a value that compares equal could hash differently.
  • Why does adding `extension Contact: Equatable {}` in a different file fail when the same line works in Contact.swift?
    Synthesis is allowed only in the original declaration or a same-file extension, so the generated code can read `private` and `fileprivate` stored properties. In another file the compiler reports "extension outside of file declaring struct 'Contact' prevents automatic synthesis of '==' for protocol 'Equatable'". Move the extension, or write `==` by hand.
  • An enum declares `Comparable`. What order does the synthesized `<` use, and when is it unavailable?
    Since Swift 5.3 the synthesized `<` orders by case declaration order, then lexicographically by associated values, which must all be `Comparable`. It is unavailable when the enum has a raw type: the compiler notes that the raw type prevents synthesized conformance. Reordering the cases changes the order.

  • Every Swift struct is Equatable automatically without declaring it.
  • Declaring Equatable on a class makes the compiler compare its stored properties.
  • Writing only == is enough; the synthesized hash(into:) will match it.
  • Synthesis works from an extension in any file of the module.
  • Structs whose properties are all Comparable get a synthesized <.

Assumes Swift 6.4: since 6.4 (SE-0499) Equatable, Hashable and Comparable accept ~Copyable types; the struct and enum synthesis rules date from Swift 4.1 and 5.3.

open as a page

In Swift, how do you sort contacts by last name and then first name, and what does each approach actually compare?

level: middleimportance: must knowfreq 58%

basics

~20 s

Compare tuples in a closure, sorted { ($0.lastName, $0.firstName) < ($1.lastName, $1.firstName) }, or make Contact Comparable with that < when the order is inherent. Foundation's KeyPathComparator sorts by key paths and compares Strings localized.

open as a page

In Swift, how should you implement hash(into:) with Hasher, and why must a hashValue never be persisted across launches?

level: middleimportance: should knowfreq 50%

basics

~10 s

Implement hash(into:) by calling hasher.combine(_:) on exactly the members == compares. Hasher is randomly seeded per execution, so hashValue changes between launches and must never be stored in files, databases or caches.

open as a page

In Swift, how do ==, ===, ObjectIdentifier and Identifiable's id differ when deciding whether two contacts are the same?

level: middleimportance: should knowfreq 55%

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.

open as a page

A Swift contacts importer deduplicates with a Set, yet contacts that compare equal with == survive as duplicates: why, and how do you fix it?

level: seniorimportance: should knowfreq 48%

basics

~20 s

Set 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.

open as a page

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?

level: principalimportance: should knowfreq 30%

basics

~20 s

Keep 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:).

open as a page