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, logical, or relational operations on one, two, or three operands. Swift operators are strictly typed and inherently safe; for example, standard arithmetic operators trap overflow conditions rather than silently truncating data.

Classification by Arity and Position

Operators are categorized by the number of operands they accept and their position relative to those operands:
  • Unary Operators: Operate on a single operand.
    • Prefix: Appears immediately before the operand (e.g., !a, -x).
    • Postfix: Appears immediately after the operand (e.g., b!).
  • Binary Operators: Operate on two operands. They are strictly infix, appearing between the operands (e.g., a + b).
  • Ternary Operators: Operate on three operands. Swift implements exactly one ternary operator, the conditional operator (a ? b : c).

Standard Operator Categories

Assignment Operator

The assignment operator (=) initializes or mutates the value of the left-hand operand with the value of the right-hand operand. Unlike C or Objective-C, the Swift assignment operator does not return a value, preventing accidental assignment within conditional statements.
let a = 10
var b = 5
b = a

Arithmetic Operators

Standard arithmetic operators (+, -, *, /, %) perform standard mathematical operations. Swift prevents arithmetic overflow by default. To explicitly allow overflow, Swift provides parallel overflow operators prefixed with an ampersand (&+, &-, &*).
let sum = 1 + 2
let remainder = 9 % 4
let overflowSum = UInt8.max &+ 1 // Evaluates to 0 instead of trapping

Compound Assignment Operators

Compound operators combine assignment (=) with another operation. The left operand must be a mutable variable (var). These operators do not return a value.
var a = 1
a += 2 // Syntactic sugar for: a = a + 2

Comparison Operators

Comparison operators evaluate the relationship between two operands and return a Bool. Swift includes standard value equality/inequality (==, !=), magnitude comparison (<, >, <=, >=), and identity operators (===, !==) which check if two object references point to the exact same memory instance.
class Instance {}
let objectA = Instance()
let objectB = objectA

let isEqual = (1 == 1)
let isIdentical = (objectA === objectB)

Logical Operators

Logical operators modify or combine Boolean logic values. The binary logical operators (&&, ||) utilize short-circuit evaluation, meaning the right-hand operand is only evaluated if the left-hand operand does not definitively determine the overall expression’s outcome.
let logicalNot = !true
let logicalAnd = true && false
let logicalOr = true || false

Nil-Coalescing Operator

The nil-coalescing operator (??) unwraps an Optional left-hand operand if it contains a value, or evaluates and returns the right-hand operand if the left-hand operand is nil. The right-hand operand must match the wrapped type of the left-hand operand, or be an optional of that same type (which allows multiple nil-coalescing operators to be chained together).
let optionalValue: String? = nil
let fallbackValue: String = "Default"
let result = optionalValue ?? fallbackValue

Range Operators

Range operators construct Range, ClosedRange, PartialRangeFrom, PartialRangeThrough, or PartialRangeUpTo types, representing a sequence of values.
  • Closed Range (...): Defines a range running from a to b, inclusive of both.
  • Half-Open Range (..<): Defines a range running from a to b, inclusive of a but exclusive of b.
  • One-Sided Range: Omits either the lower or upper bound (e.g., a..., ...b, ..<b).
let closed = 1...5
let halfOpen = 1..<5
let oneSided = ...5

Bitwise Operators

Bitwise operators manipulate the individual raw data bits within a data structure. They include Bitwise NOT (~), AND (&), OR (|), XOR (^), Left Shift (<<), and Right Shift (>>).
let invertedBits = ~0b00001111
let shiftedBits = 0b00000100 << 1

Precedence and Associativity

When multiple operators appear in a single expression, Swift relies on precedence and associativity rules to determine the evaluation order.
  • Precedence: Higher precedence operators are evaluated before lower precedence operators (e.g., multiplication is evaluated before addition).
  • Associativity: Determines how operators of the exact same precedence are grouped—either left-associative (grouped left-to-right) or right-associative (grouped right-to-left).

Custom Operators and Overloading

Swift permits the overloading of existing operators for custom types and the declaration of entirely new custom operators. Custom operators are defined at the global scope using the operator keyword, modified by prefix, infix, or postfix. Infix operators can optionally specify a precedencegroup to define their precedence and associativity relative to standard operators. If a precedence group is omitted, Swift automatically assigns the operator to the DefaultPrecedence group.
import Foundation

// 1. Define the custom operator and its precedence group
infix operator **: MultiplicationPrecedence

// 2. Implement the operator's behavior for specific types
func ** (lhs: Double, rhs: Double) -> Double {
    return pow(lhs, rhs)
}
Master Swift with Deep Grasping Methodology!Learn More