0Pricing
Swift Academy · Lesson

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

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