Operators in Swift
Arithmetic, comparison, and logical operators, plus the range operators Swift uses everywhere.
2 min read
Most of Swift's operators look like what you already know from other languages, with a couple of Swift-specific additions worth calling out.
Arithmetic and compound assignment
let sum = 5 + 3 // 8
let difference = 5 - 3 // 2
let product = 5 * 3 // 15
let quotient = 5 / 3 // 1 — integer division truncates
let remainder = 5 % 3 // 2
var total = 10
total += 5 // 15
total -= 2 // 13
total *= 2 // 26Note that 5 / 3 on two Int values gives 1, not 1.666... — integer division always truncates toward zero. If you want a decimal result, at least one operand needs to be a Double: 5.0 / 3.0 gives 1.6666666666666667.
Comparison and logical operators
let isAdult = 20 >= 18 // true
let isEqual = "cat" == "dog" // false
let canVote = isAdult && true // && is logical AND
let canEnter = isAdult || false // || is logical OR
let isMinor = !isAdult // ! negates a BoolThese behave exactly as expected, with one important detail: && and || short-circuit — in a && b, if a is false, b is never evaluated at all. This matters when the second operand has a side effect or could crash:
let list: [Int] = []
if !list.isEmpty && list[0] == 1 {
// safe: list[0] is only checked if list is non-empty
}Range operators
Swift has dedicated operators for expressing a range of values, used constantly with loops and array slicing:
let closedRange = 1...5 // 1, 2, 3, 4, 5 — includes both ends
let halfOpen = 1..<5 // 1, 2, 3, 4 — excludes the upper bound
for i in 1...3 {
print(i) // prints 1, 2, 3
}
let numbers = [10, 20, 30, 40, 50]
print(numbers[1..<3]) // [20, 30]The closed range ... includes both endpoints; the half-open range ..< excludes the upper one — useful for indexing into arrays, since a collection with count elements has valid indices 0..<count.
The nil-coalescing operator, revisited
You've already seen ?? in the optionals lessons — it's worth remembering it as an operator in its own right, alongside these others, since it follows the same left-to-right evaluation rules:
let a: Int? = nil
let b = a ?? 0 + 1 // careful: this is a ?? (0 + 1), i.e. 1 — not (a ?? 0) + 1Precedence rules like this are worth double-checking with parentheses whenever an expression mixes several operators and the result isn't obvious at a glance — it costs nothing and removes any ambiguity for the next reader.