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) // 1All lessons in this course
- Operator overloading & precedence groups
- Subscripts & custom indices revisited
- Hashable/Equatable/Comparable derivations