Fundamentals 8 min read

Understanding Compiler Synthesis of Equatable and Hashable in Swift 4.1

This article explains how Swift 4.1's compiler can automatically synthesize Equatable and Hashable implementations, the necessary conditions, examples of enums and structs, the limitations of synthesis, and how developers can override or supplement the generated code for better performance and correctness.

Liulishuo Tech Team
Liulishuo Tech Team
Liulishuo Tech Team
Understanding Compiler Synthesis of Equatable and Hashable in Swift 4.1

Compiler synthesis is a powerful feature that frees developers from repetitive boilerplate code. In Swift 4.0, the Codable protocol could be synthesized, and Swift 4.1 extended synthesis to Equatable and Hashable . The compiler can only generate these conformances when all stored properties of a type also conform to the respective protocols.

Key concepts reviewed include the relationship between equality and hash values: equal objects must have identical hash values, but identical hash values do not guarantee equality. In Swift, Hashable inherits from Equatable , so any Hashable type is also Equatable . When overriding == , developers must keep hashValue consistent, and vice‑versa. Dictionary and Set keys must be Hashable .

1. Synthesizing Equatable

Previously developers wrote verbose implementations of == . With synthesis, simply declaring : Equatable lets the compiler generate the equality function. However, when certain properties should be excluded from comparison (e.g., a creation timestamp), a manual implementation is still required.

struct Person: Equatable {
    static func == (lhs: Person, rhs: Person) -> Bool {
        return lhs.firstName == rhs.firstName &&
               lhs.lastName == rhs.lastName &&
               lhs.birthDate == rhs.birthDate
    }
}

Now the same type can be written as:

struct Person: Equatable { ... }

Enum synthesis before Swift 4.1 works for simple enums and raw‑value enums, but not for enums with associated values. After Swift 4.1, declaring : Equatable on such enums is sufficient for the compiler to synthesize == .

enum Token {
    case string(String)
    case number(Int)
    case lparen
    case rparen
}
// Swift 4.1: just add :Equatable and the compiler creates ==

2. Synthesizing Hashable

Similarly, adding : Hashable lets the compiler generate a hashValue implementation. The article revisits the purpose of hash functions, emphasizing the trade‑off between collision avoidance and performance, and notes that compiler‑generated hashes are safe but may not be optimal because the compiler lacks domain‑specific knowledge (e.g., valid ranges of property values).

Developers can still provide custom hashValue implementations to improve distribution or to incorporate additional constraints.

There are cases where synthesis does not occur: classes (due to inheritance complexities) and extensions that add Hashable or Equatable conformance.

Other: Standard Library Index Types

Swift 4.1 also makes many standard library index types Hashable , enabling their use in keyed collections and key‑path expressions. For example, String.Index becomes hashable, allowing key‑path subscripting with indices.

let numbers = [10, 20, 30, 40, 50]
let firstValue = \[Int].[0]
print(numbers[keyPath: firstValue]) // 10

let string = "Helloooo!"
let firstChar = \String.[string.startIndex] // valid in Swift 4.1 or later

Summary

The value of synthesizing Equatable and Hashable lies in reducing boilerplate and preventing errors.

Limitations exist; developers must manually implement these protocols when properties should be excluded or when dealing with classes and extensions.

Standard library enhancements, such as making index types hashable, expand the expressive power of Swift’s type system.

iOScompilerProgrammingSwiftEquatableHashableSynthesis
Liulishuo Tech Team
Written by

Liulishuo Tech Team

Help everyone become a global citizen!

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.