Operator overloading & precedence groups
Overload built-in operators for your types and define precedence groups so expressions parse as intended. Keep designs minimal and predictable.
Why customize operators?
Swift lets you overload operators for your types and create new ones. Use them sparingly: prefer clarity, document behavior, and define precedence to avoid surprises.
Overloading a built-in operator
Overload an existing operator by writing a free function with the same symbol and your type. Keep semantics predictable (e.g., + adds values).
struct Vector2D: CustomStringConvertible, Equatable {
var x: Double
var y: Double
var description: String { "(\(x), \(y))" }
}
func + (lhs: Vector2D, rhs: Vector2D) -> Vector2D {
Vector2D(x: lhs.x + rhs.x, y: lhs.y + rhs.y)
}
func == (lhs: Vector2D, rhs: Vector2D) -> Bool {
lhs.x == rhs.x && lhs.y == rhs.y
}
let a = Vector2D(x: 1, y: 2)
let b = Vector2D(x: 3, y: 4)
let c = a + b
print(c) // (4.0, 6.0)All lessons in this course
- Operator overloading & precedence groups
- Subscripts & custom indices revisited
- Hashable/Equatable/Comparable derivations