In Swift, when does the compiler synthesize Equatable and Hashable for your own type, and when must you write them yourself?
answer
- you have to ask for it
- every stored property must conform
- payload-free enums need no declaration
- same file as the type
- classes are left out
basics
~20 sSwift 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 sSynthesis 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 linesstruct 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 truego deeper
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.
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.
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.
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.