Comparable / Hashable / Equatable
Swift provides standard protocols — Equatable, Comparable, and Hashable — that enable equality checks, ordering comparisons, and hashing for your types.
Protocol Overview
| Protocol | Description |
|---|---|
| Equatable | Enables equality comparison using the == operator. |
| Comparable | Inherits from Equatable and enables ordering with the < operator. The <= / > / >= operators are synthesized automatically. |
| Hashable | Inherits from Equatable and allows the type to be used as a key in Set or Dictionary. |
| Identifiable | Requires a unique id property. Commonly used with SwiftUI. |
Sample Code
// Equatable: equality check
struct Point: Equatable {
var x: Double
var y: Double
// Implementing == explicitly (can also be synthesized automatically)
static func == (lhs: Point, rhs: Point) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y
}
}
let p1 = Point(x: 1.0, y: 2.0)
let p2 = Point(x: 1.0, y: 2.0)
let p3 = Point(x: 3.0, y: 4.0)
print("p1 == p2: \(p1 == p2)")
print("p1 == p3: \(p1 == p3)")
// Comparable: ordering comparison
struct Student: Comparable {
let name: String
let score: Int
// Only < needs to be implemented; <= / > / >= are synthesized automatically
static func < (lhs: Student, rhs: Student) -> Bool {
return lhs.score < rhs.score
}
}
let students = [
Student(name: "Alice", score: 85),
Student(name: "Bob", score: 92),
Student(name: "Carol", score: 78)
]
let sorted = students.sorted()
for s in sorted {
print("\(s.name): \(s.score) points")
}
// Hashable: use as a key in Set or Dictionary
struct Color: Hashable {
let r: Int, g: Int, b: Int
}
var colorSet: Set<Color> = [
Color(r: 255, g: 0, b: 0),
Color(r: 0, g: 255, b: 0),
Color(r: 255, g: 0, b: 0) // Duplicates are removed
]
print("Number of colors: \(colorSet.count)")
Notes
If all stored properties of a struct or enum already conform to Equatable or Hashable, the compiler can synthesize conformance automatically. You can omit implementations of == and hashValue.
For Comparable, you only need to implement <; the compiler generates the remaining operators (<=, >, >=) for you. Types conforming to Hashable must guarantee that if two values are equal (==), they have the same hashValue — this is the Hashable contract.
For the basics of protocols, see Protocol basics / Conformance.
If you find any errors or copyright issues, please contact us.