Custom Operators in Swift
From the Swift cheat sheet · Operators · verified Jul 2026
Custom Operators
Defining and implementing custom operators
swift
// Operator overloading
struct Vector2D {
var x: Double
var y: Double
}
// Addition operator
extension Vector2D {
static func + (lhs: Vector2D, rhs: Vector2D) -> Vector2D {
return Vector2D(x: lhs.x + rhs.x, y: lhs.y + rhs.y)
}
static func - (lhs: Vector2D, rhs: Vector2D) -> Vector2D {
return Vector2D(x: lhs.x - rhs.x, y: lhs.y - rhs.y)
}
static func * (vector: Vector2D, scalar: Double) -> Vector2D {
return Vector2D(x: vector.x * scalar, y: vector.y * scalar)
}
}
// Compound assignment
extension Vector2D {
static func += (lhs: inout Vector2D, rhs: Vector2D) {
lhs = lhs + rhs
}
}
// Custom operators
prefix operator +++
prefix func +++ (value: inout Int) -> Int {
value += 2
return value
}
infix operator **: MultiplicationPrecedence
func ** (base: Double, power: Double) -> Double {
return pow(base, power)
}💡 Operator overloading must match existing operator signatures
⚡ Custom operators need explicit precedence and associativity
📌 Use ~= to enable pattern matching in switch statements
🟢 Keep custom operators simple and intuitive