Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

An operator in Swift is a specialized lexical token—typically a symbol or a short phrase—that performs computations, assignments, or relational checks on one, two, or three operands. Swift operators are strictly typed, do not perform implicit type coercion, and are designed to prevent undefined behavior (such as trapping on arithmetic overflow by default). Operators are classified by their arity (the number of operands they take) and their spatial position relative to those operands:
  • Unary Operators: Operate on a single target.
    • Prefix: Positioned immediately before the operand without whitespace (-a, !b).
    • Postfix: Positioned immediately after the operand without whitespace (c!, d...).
  • Binary Operators: Operate on two targets. They are strictly infix, positioned between the two operands (a + b). Swift requires consistent whitespace on both sides of a binary operator.
  • Ternary Operators: Operate on three targets. Swift implements exactly one ternary operator: the conditional operator (a ? b : c).
let x = 5
let y = 10
let isValid = false
let optionalValue: String? = "Data"
let fallbackValue = "Fallback"
let condition = true
let trueResult = 1
let falseResult = 0

// Unary Prefix
let negation = -x
let logicalNot = !isValid

// Unary Postfix
let forcedUnwrap = optionalValue!

// Binary Infix
let addition = x + y
let nilCoalescing = optionalValue ?? fallbackValue

// Ternary
let evaluation = condition ? trueResult : falseResult

Core Operator Mechanics

Assignment Operator (=) Unlike in C or Objective-C, the assignment operator in Swift does not return a value. This architectural decision prevents the common error of using = when the equality operator (==) is intended within conditional statements. Compound Assignment Operators (+=, -=, *=, /=, etc.) Swift provides compound operators that combine assignment with another operation. Sharing the semantic behavior of the standard assignment operator, compound assignment operators do not return a value. Consequently, they cannot be chained or evaluated as expressions.
var counter = 0
counter += 5 // Valid mutation
// let result = (counter += 5) // Compile-time error: returns 'Void'
Identity Operators (===, !==) Identity operators evaluate reference identity. They are used exclusively with reference types (classes) to determine whether two variables or constants point to the exact same instance in memory. This is fundamentally distinct from the equality operators (==, !=), which evaluate whether the underlying values are equivalent.
class Node {}
let nodeA = Node()
let nodeB = nodeA
let nodeC = Node()

let isSameReference = (nodeA === nodeB) // true
let isDifferentReference = (nodeA !== nodeC) // true
Arithmetic Operators (+, -, *, /, %) Standard arithmetic operators in Swift detect and trap on overflow or underflow, triggering a runtime crash rather than allowing silent data corruption. The remainder operator (%) operates strictly on integers. To calculate the remainder of floating-point numbers, developers must use the truncatingRemainder(dividingBy:) method. Overflow Operators (&+, &-, &*) To explicitly permit two’s-complement overflow behavior, Swift provides dedicated overflow operators prefixed with an ampersand. These operators truncate the available bits rather than trapping.
var unsignedMax = UInt8.max
// unsignedMax = unsignedMax + 1 // Runtime error (Overflow)
unsignedMax = unsignedMax &+ 1   // Wraps to 0
Range Operators (..., ..<) Swift defines specific operators to construct Range and ClosedRange types.
  • Closed Range (a...b): Defines a range running from a to b, inclusive.
  • Half-Open Range (a..<b): Defines a range running from a to b, excluding b.
  • One-Sided Range (a..., ...b, ..<b): Omits one boundary, inferring the start or end from context (e.g., array bounds).
Logical Operators (!, &&, ||) Binary logical operators (&&, ||) implement short-circuit evaluation. The right-hand operand is only evaluated if the left-hand operand does not conclusively determine the overall expression’s boolean state.

Precedence and Associativity

Swift resolves complex expressions using strict precedence and associativity rules, managed through precedencegroup declarations.
  • Precedence dictates the order of operations (e.g., multiplication is evaluated before addition).
  • Associativity dictates how operators of the same precedence level are grouped (left, right, or none).

Custom Operators

Swift allows the definition of custom operators using the operator keyword at the global scope. Developers must specify the position (prefix, infix, or postfix). For infix operators, a precedencegroup can be assigned to define its evaluation hierarchy relative to standard operators. If a precedence group is omitted, Swift automatically assigns the operator to DefaultPrecedence, which has no associativity and a precedence immediately higher than TernaryPrecedence.
import Foundation

// 1. Define a precedence group (Optional, defaults to DefaultPrecedence if omitted)
precedencegroup ExponentiationPrecedence {
    associativity: right
    higherThan: MultiplicationPrecedence
}

// 2. Declare the operator
infix operator ** : ExponentiationPrecedence

// 3. Implement the operator function
func ** (base: Double, power: Double) -> Double {
    return pow(base, power)
}
Master Swift with Deep Grasping Methodology!Learn More