← Back to blog

Basic operators

Arithmetic, comparison, logical, ternary, range and the nil-coalescing operator in modern Swift. Second post in the Swift Basics series.

In this second post of the series we explore operators in modern Swift. These are the tools you’ll use in practically every line of code: to calculate, compare, combine conditions and handle nil values. Some like ?? are unique to Swift and you’ll use them constantly.

Arithmetic operators

The classics. Swift supports them all and they behave exactly as you’d expect.

let sum        = 10 + 5   // 15
let difference = 10 - 5   // 5
let product    = 10 * 5   // 50
let quotient   = 10 / 3   // 3  (integer division, not 3.33)
let remainder  = 10 % 3   // 1  (what's left over from the division)

// With decimals, division does give a decimal result
let decimalDiv = 10.0 / 3.0  // 3.3333...

The % (modulo/remainder) operator is very useful for checking if a number is even or odd, or for cycling through array indices.

// Classic trick: even or odd
let number = 7
if number % 2 == 0 {
    print("Even")
} else {
    print("Odd")  // this prints
}

Compound assignment operators

Combine an arithmetic operation with assignment. They’re a very common shorthand for modifying variables.

var points = 100

points += 25   // equivalent to: points = points + 25  → 125
points -= 10   // equivalent to: points = points - 10  → 115
points *= 2    // equivalent to: points = points * 2   → 230
points /= 5    // equivalent to: points = points / 5   → 46
points %= 10   // equivalent to: points = points % 10  → 6

Comparison operators

Compare two values and return a Bool (true or false). They’re the foundation of all conditions in your code.

let a = 10
let b = 20

print(a == b)   // false  — equal to
print(a != b)   // true   — not equal to
print(a <  b)   // true   — less than
print(a >  b)   // false  — greater than
print(a <= b)   // true   — less than or equal to
print(a >= b)   // false  — greater than or equal to

// Also work with Strings
let status = "active"
print(status == "active")   // true
print(status != "inactive") // true

Logical operators

Combine or invert boolean conditions. Essential for building compound conditions.

let isUserActive = true
let hasSubscription = false

// AND — both conditions must be true
if isUserActive && hasSubscription {
    print("Full access")
}

// OR — at least one condition must be true
if isUserActive || hasSubscription {
    print("Partial access")  // this prints
}

// NOT — inverts the boolean value
if !hasSubscription {
    print("No active subscription")  // this prints
}

Ternary operator

A compact way to write an if/else in a single line. Very useful when assigning a value based on a condition.

// Syntax: condition ? valueIfTrue : valueIfFalse
let age = 20
let access = age >= 18 ? "Allowed" : "Denied"
print(access)  // "Allowed"

// Equivalent to:
let accessLong: String
if age >= 18 {
    accessLong = "Allowed"
} else {
    accessLong = "Denied"
}

// In SwiftUI you'll see it a lot for toggling between values
let temperature = 35.0
let icon = temperature > 30 ? "☀️" : "🌥️"

Use it in moderation — if the condition is complex or the result requires extra logic, a traditional if/else is better for readability.

Range operators

Swift has two range operators you’ll see constantly when working with collections and loops.

// Closed range (...) — includes both endpoints
for i in 1...5 {
    print(i)  // 1, 2, 3, 4, 5
}

// Half-open range (..<) — excludes the upper endpoint
for i in 0..<5 {
    print(i)  // 0, 1, 2, 3, 4
}

// Half-open range is ideal for iterating arrays (0-based)
let fruits = ["Apple", "Pear", "Grape"]
for i in 0..<fruits.count {
    print("\(i): \(fruits[i])")
}

// Ranges in switch
let grade = 85
switch grade {
case 90...100: print("Excellent")
case 70..<90:  print("Passing")    // this prints
case 0..<70:   print("Failing")
default:       print("Invalid")
}

Nil-coalescing operator ??

This is one of Swift’s most characteristic operators. It works with optionals (values that can be nil) and lets you define a default value when the optional is empty. You’ll see it in almost any real project.

// Syntax: optional ?? defaultValue
let username: String? = nil
let name = username ?? "Guest"
print(name)  // "Guest"

let savedValue: String? = "Swift"
let result = savedValue ?? "Default value"
print(result)  // "Swift" — uses the real value because it's not nil

// Practical case: reading from UserDefaults or other optional sources
let savedLanguage: String? = nil
let language = savedLanguage ?? "en"
print(language)  // "en"

Optionals are explained in detail in The Basics 04 of this series, but it’s important to know ?? from the start because you’ll encounter it in almost every Swift example.

Summary

  • Arithmetic (+, -, *, /, %): basic math operations.
  • Compound assignment (+=, -=…): modify a variable and assign in one step.
  • Comparison (==, !=, <, >…): compare values, return Bool.
  • Logical (&&, ||, !): combine or invert conditions.
  • Ternary (? :): compact if/else for value assignment.
  • Range (…, ..<): define intervals, ideal in loops and switch.
  • Nil-coalescing (??): default value when an optional is nil.

In the next post we’ll look at Control Flowif, switch, loops and the powerful guard that changes the way you structure your code.