0Pricing
Swift Academy · Lesson

Hashable/Equatable/Comparable derivations

Let Swift synthesize Equatable/Hashable (and Codable) for simple structs/enums; implement custom Comparable (lexicographic) and manual hash(into:) when needed.

What gets synthesized?

Swift can synthesize common conformances for simple types:

  • Equatable: value equality
  • Hashable: dictionary/set keys
  • Codable: encode/decode

Implement Comparable yourself (lexicographic) or rely on enum case order when applicable.

Synthesis for structs

For structs whose stored properties are Equatable/Hashable, Swift generates both automatically.

struct Point: Equatable, Hashable {
    var x: Int
    var y: Int
    // No extra code: Equatable & Hashable are synthesized
}
let p1 = Point(x: 1, y: 2)
let p2 = Point(x: 1, y: 2)
print(p1 == p2)                 // true
let set: Set<Point> = [p1, p2]  // Hashable works; duplicates coalesce
print(set.count)                // 1

All lessons in this course

  1. Operator overloading & precedence groups
  2. Subscripts & custom indices revisited
  3. Hashable/Equatable/Comparable derivations
← Back to Swift Academy