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 mathematical, relational, logical, or bitwise operations on one or more operands. Swift operators are strictly typed, enforce memory safety by trapping on overflow by default, and support custom definitions with explicit precedence and associativity.

Classification by Arity and Fixity

Operators are categorized by the number of operands they accept (arity) and their position relative to those operands (fixity).
  • Unary Operators: Operate on a single operand.
    • Prefix: Placed immediately before the operand without whitespace.
let b = 5 let a = -b let d = true let c = !d
    *   **Postfix:** Placed immediately after the operand without whitespace.
    ```swift
let f: Int? = 10
let e = f!
  • Binary Operators: Operate on two operands. They are always infix, placed between the two operands. Swift requires consistent whitespace on both sides of a binary operator to resolve ambiguity.
let h = 3
let i = 4
let g = h + i
  • Ternary Operators: Operate on three operands. Swift implements a single ternary conditional operator.
let condition = true
let trueValue = 10
let falseValue = 20
let j = condition ? trueValue : falseValue

Core Operator Categories

Assignment Operator The assignment operator (=) initializes or mutates a value. Unlike in C or Objective-C, the assignment operator in Swift does not return a value. This design prevents accidental assignment within conditional statements.
var x = 5
let y = 10
x = y
Arithmetic Operators Standard arithmetic operators (+, -, *, /, %) perform mathematical operations. Swift prevents silent arithmetic overflow; operations that exceed the bounds of the type will trigger a runtime trap.
let sum = 5 + 3
let remainder = 10 % 3
Note: To explicitly permit overflow, Swift provides specialized overflow operators (&+, &-, &*). Comparison and Identity Operators Comparison operators evaluate to a Bool. Identity operators (===, !==) check whether two object references point to the exact same instance in memory, which is distinct from value equality (==).
let val1 = 5
let val2 = 5
let isEqual = val1 == val2 // Value equality

class ReferenceType {}
let ref1 = ReferenceType()
let ref2 = ref1
let isIdentical = ref1 === ref2 // Reference identity
Nil-Coalescing Operator The nil-coalescing operator (??) unwraps an optional type if it contains a value, or falls back to a default value if the optional is nil. It utilizes short-circuit evaluation; the right-hand operand is not evaluated if the left-hand operand is non-nil.
let optionalValue: String? = nil
let fallbackValue = "Default String"
let result = optionalValue ?? fallbackValue
Range Operators Swift provides specialized operators to construct Range and ClosedRange types.
  • Closed Range (...): Defines a range running from the lower bound to the upper bound, inclusive.
  • Half-Open Range (..<): Defines a range running from the lower bound to the upper bound, exclusive of the upper bound.
  • One-Sided Range: Omits either the lower or upper bound to create a partial range.
let start = 1
let end = 5
let closed = start...end
let halfOpen = start..<end
let oneSided = start...
Logical and Bitwise Operators
  • Logical: (!, &&, ||) Operate on boolean logic. The && and || operators employ short-circuit evaluation.
  • Bitwise: (~, &, |, ^, <<, >>) Manipulate the raw data bits within a data structure.

Precedence and Associativity

Infix operators are governed by precedence and associativity rules, which dictate the parsing order of complex expressions without explicit parentheses.
  • Precedence: Determines which operator binds tighter to its operands (e.g., multiplication has higher precedence than addition).
  • Associativity: Determines how operators of the exact same precedence are grouped (left-associative or right-associative).

Custom Operators

Swift allows the declaration of custom operators using the operator keyword. Custom operators must be declared at the global scope and assigned a fixity (prefix, infix, or postfix). Infix operators can optionally be assigned to a precedencegroup to define their evaluation order relative to other operators. If a precedence group is not explicitly specified, Swift automatically assigns the custom infix operator to a default precedence group (DefaultPrecedence), which has a precedence immediately higher than the ternary conditional operator.
import Foundation

prefix operator +++
infix operator ** : MultiplicationPrecedence

extension Int {
    static prefix func +++ (vector: inout Int) {
        vector += 2
    }
    
    static func ** (left: Int, right: Int) -> Int {
        return Int(pow(Double(left), Double(right)))
    }
}

var myVector = 3
+++myVector // Mutates myVector to 5

let powerResult = 2 ** 3 // Evaluates to 8
Master Swift with Deep Grasping Methodology!Learn More