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.

Operator overloading & precedence groups is a free Swift Academy lesson on CoddyKit — lesson 1 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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)

Custom operator + precedence

Declare a precedencegroup and attach it to your operator. Right associativity makes 2 ** 3 ** 2 parse as 2 ** (3 ** 2).

// Define power operator ** with right-associative precedence
precedencegroup PowerPrecedence {
    higherThan: MultiplicationPrecedence
    associativity: right
}
infix operator ** : PowerPrecedence

// Simple integer exponent (education-only; no overflow checks)
func ** (base: Int, exp: Int) -> Int {
    guard exp >= 0 else { return 0 }   // keep it simple for demo
    if exp == 0 { return 1 }
    var result = 1
    for _ in 0..<exp { result *= base }
    return result
}
print(2 ** 3)          // 8
print(2 ** 3 ** 2)     // 2 ** (3 ** 2) = 2 ** 9 = 512 (right-assoc)

Prefix/postfix operators

You can define prefix/postfix operators. Reserve these for clear math-like domains; avoid surprising meanings.

prefix operator √
prefix func √ (x: Double) -> Double { x.squareRoot() }

postfix operator !
postfix func ! (x: Bool) -> Bool { !x }  // purely demo; avoid confusing overrides

print(√9)     // 3.0
print(true!)  // false (demo only — don't ship this)

Precedence in practice

Place your precedence carefully relative to built-ins (e.g., MultiplicationPrecedence). Test expressions to confirm readability and intent.

// Demonstrate how precedence affects parsing
// Our PowerPrecedence is higher than Multiplication.
// So this parses as: 2 * (3 ** 2) = 18
let r1 = 2 * 3 ** 2
print(r1)

// Compare if we had lower precedence (hypothetical):
// Then it would parse as (2 * 3) ** 2 = 36

Best practices

Guidelines:

  • Prefer methods for non-standard actions; reserve operators for familiar math/bitwise ops.
  • Match user expectations (+ adds, * multiplies).
  • Document custom operators and keep the set small.
  • Define precedence and associativity to avoid ambiguous parsing.

Declaring operators correctly

Quick check: Which is the correct way to add a new operator with a precedence group?

Recap

Recap: Overload operators only when semantics are obvious; define precedence groups and associativity to control parsing; test expressions for clarity.

Frequently asked questions

Is the “Operator overloading & precedence groups” lesson free?

Yes — the full text of “Operator overloading & precedence groups” is free to read here on the web, and the Swift Academy course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Swift Academy course, upgrade to CoddyKit PRO.

What will I learn in “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. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Swift Academy?

No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 3, so you can start here or from the beginning and move at your own pace.

How long does the “Operator overloading & precedence groups” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Swift Academy lesson?

Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

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