skip to content

A teammate wants `+` on a Swift `Vector2D` struct and a new `•` dot-product operator; how is each declared, and what does a `precedencegroup` decide?

level: seniorimportance: should knowfreq 28%

answer

  1. overload versus declare
  2. file-scope operator declaration
  3. higherThan, lowerThan, associativity
  4. DefaultPrecedence is barely ordered

basics

~20 s

Overloading + needs only a static func + on Vector2D, which keeps AdditionPrecedence. A new • needs a file-scope infix operator declaration naming a precedencegroup, which fixes how tightly it binds against other groups and how a run of it associates.

solid answer

~40 s

An existing operator is overloaded by adding `static func + (lhs: Vector2D, rhs: Vector2D) -> Vector2D` to the type; it keeps `+`'s precedence. `+=` is not derived, but conforming to `AdditiveArithmetic` (`zero`, `+`, `-`) supplies `+=` and `-=` by default. A new operator is first declared at file scope, as in `infix operator •: DotProductPrecedence`, then implemented as a static method. The `precedencegroup` sets `higherThan` and `lowerThan` relations, `associativity` (`left`, `right` or `none`, the default) and `assignment`. Without a group, an infix operator gets `DefaultPrecedence`, which is declared only higher than the ternary's group and is non-associative, so `a <+> b + c` fails with "adjacent operators are in unordered precedence groups" until you add parentheses or a group.

code

swift · 29 lines
swift
precedencegroup DotProductPrecedence {
    associativity: none
    higherThan: AdditionPrecedence
    lowerThan: MultiplicationPrecedence
}
infix operator •: DotProductPrecedence

struct Vector2D: AdditiveArithmetic {
    var x: Double
    var y: Double
    static let zero = Vector2D(x: 0, y: 0)

    static func + (lhs: Vector2D, rhs: Vector2D) -> Vector2D {
        Vector2D(x: lhs.x + rhs.x, y: lhs.y + rhs.y)
    }
    static func - (lhs: Vector2D, rhs: Vector2D) -> Vector2D {
        Vector2D(x: lhs.x - rhs.x, y: lhs.y - rhs.y)
    }
    static func • (lhs: Vector2D, rhs: Vector2D) -> Double {
        lhs.x * rhs.x + lhs.y * rhs.y
    }
}

let a = Vector2D(x: 1, y: 2)
let b = Vector2D(x: 3, y: 4)
var total = Vector2D.zero
total += a                      // += comes from AdditiveArithmetic
print(a • b + 1)                // 12.0: • binds tighter than +
print([a, b].reduce(.zero, +))  // Vector2D(x: 4.0, y: 6.0)

go deeper

for a junior

Recall that an existing operator is overloaded with a static func on the type, while a new symbol needs an infix, prefix or postfix operator declaration first.

for a middle

Explain where the operator declaration lives, why += needs its own implementation or AdditiveArithmetic, and what higherThan and associativity do.

for a senior

Place a custom operator deliberately: pick its group's relations and associativity from how it should read, and know the DefaultPrecedence traps before reviewers hit them.

for a principal

Judge whether a new operator is worth its precedence rules and discoverability cost, and prefer conformances that give standard operators their usual meaning.

## Overloading an existing operator Giving `Vector2D` a `+` needs no new syntax: `+` is already declared by the standard library as `infix operator +: AdditionPrecedence`, so you only add an implementation, a `static func` named after the operator on one of the operand types. - `static func + (lhs: Vector2D, rhs: Vector2D) -> Vector2D` makes `a + b` work, with `+`'s existing precedence and left associativity. - `+=` is **not** derived from `+`. Writing `p += q` with only `+` defined fails to type-check. Either write `static func += (lhs: inout Vector2D, rhs: Vector2D)`, or conform to `AdditiveArithmetic`, whose requirements are `zero`, `+`, `-`, `+=` and `-=`, with default implementations of `+=` and `-=` supplied by the standard library. - A conformance also unlocks generic code: `[a, b].reduce(.zero, +)` works because `Vector2D.zero` exists. ## Declaring a new operator A brand-new symbol such as `•` must be **declared** before it can be implemented: 1. Declare it at file scope: `infix operator •: DotProductPrecedence`. Inside a type the compiler says `'operator' may only be declared at file scope`. 2. Implement it as a `static func •` on one of the operand types. Without the declaration, the compiler reports `operator implementation without matching operator declaration`. 3. For `prefix` or `postfix` operators, mark the implementing method `prefix` or `postfix` too. Those fixities take no precedence group; when both apply to one operand, the postfix operator applies first. Operator names come from a fixed character set: they start with one of `/ = - + ! * % < > & | ^ ? ~` or certain Unicode symbol characters, and only operators that begin with a dot may contain more dots. ## What a precedence group decides A `precedencegroup` declaration answers the questions the parser asks when operators sit next to each other without parentheses: | Attribute | Meaning | Default | |---|---|---| | `higherThan:` | this group binds tighter than the named groups | no relation | | `lowerThan:` | this group binds looser than the named groups; only groups from **other** modules | no relation | | `associativity:` | `left`, `right` or `none` for a run of same-group operators | `none` | | `assignment:` | whether the operator groups like assignment inside optional chaining | `false` | Relations need not form a single line. Two groups with no path between them are **unordered**, and operators from them cannot sit next to each other without parentheses. Naming a same-module group in `lowerThan:` is rejected with `precedence group cannot be given lower precedence than group in same module; make the other precedence group higher than this one instead`. ## The default group and why it bites An infix operator declared without a group gets `DefaultPrecedence`, which the standard library declares with only `higherThan: TernaryPrecedence` and no associativity. That has two consequences, both shown in the second example: - `1 <+> 2 <+> 3` fails: `adjacent operators are in non-associative precedence group 'DefaultPrecedence'`. - `1 <+> 2 + 3` and `1 <+> 2 == 3` fail: `adjacent operators are in unordered precedence groups 'DefaultPrecedence' and 'AdditionPrecedence'` (and `'ComparisonPrecedence'`), because `DefaultPrecedence` has no relation to either. So "no group" does not mean "the same as `+`"; it means "needs parentheses next to almost everything". ## Placing the dot product A dot product of two vectors returns a `Double`, and you want `a • b + 1` to mean `(a • b) + 1`. Hence the group in the first example: higher than `AdditionPrecedence`, lower than `MultiplicationPrecedence`, and `associativity: none`, because `a • b • c` is meaningless: the left result is a `Double`, not a vector. The resulting rules: - `a • b + 1` parses as `(a • b) + 1`. - `a • b == 11` works, since `ComparisonPrecedence` is below `AdditionPrecedence` and so below this group. - `a • b • c` is a compile error, which is what you want. A note on the standard groups: `&` lives in `MultiplicationPrecedence` and `|` and `^` in `AdditionPrecedence`, so `a + b & c` groups as `a + (b & c)`. Do not assume another language's precedence table when placing a custom operator.

  • Why does `lowerThan:` refuse a group from the same module?
    The compiler requires relations inside one module to be written from the higher side, and reports "precedence group cannot be given lower precedence than group in same module; make the other precedence group higher than this one instead". `lowerThan:` exists for placing your group below one you do not own, such as a standard-library group.
  • Can a protocol require an operator?
    Yes: a protocol can list `static func •(lhs: Self, rhs: Self) -> Double` as a requirement, the way `Equatable` requires `==`. The `infix operator` declaration itself still lives at file scope; the protocol only requires an implementation of an operator that is already declared.

  • Writing static func • on the type is enough to create the operator
  • An infix operator without a group gets the same precedence as +
  • associativity defaults to left when a precedencegroup omits it
  • lowerThan can name any group, including one in the same module
  • Implementing + automatically provides +=
  • An operator can be declared inside the type that implements it