Skip to content

Basic Operators

This guide covers Swift’s core operators for performing operations like assignment, arithmetic, comparison, and logical operations.

Operator Types

Operators are symbols or phrases that manipulate values:

  • Unary: Operate on one value (e.g., -x).
    • Prefix: Before the value (e.g., !flag).
    • Postfix: After the value (e.g., optional!).
  • Binary: Operate on two values (e.g., 2 + 3).
  • Ternary: Operate on three values (e.g., condition ? value1 : value2).

Assignment Operator

The assignment operator (=) sets or updates a variable’s value:

swift
let maxSpeed = 120
var currentSpeed = 60
currentSpeed = maxSpeed // currentSpeed is now 120

Assign multiple values using tuples:

swift
let (x, y) = (10, 20) // x is 10, y is 20

Unlike C, Swift’s assignment operator doesn’t return a value, preventing accidental use instead of ==.

Arithmetic Operators

Swift supports standard arithmetic operators:

  • Addition (+)
  • Subtraction (-)
  • Multiplication (*)
  • Division (/)
swift
let sum = 5 + 3 // 8
let difference = 5 - 3 // 2
let product = 4 * 2 // 8
let quotient = 10.0 / 4.0 // 2.5

String concatenation with +:

swift
let message = "Good" + "Morning" // GoodMorning

Swift prevents arithmetic overflow by default. Use overflow operators (e.g., &+) for explicit overflow behavior (see Advanced Operators).

Remainder Operator

The remainder operator (%) returns the remainder after division:

swift
let remainder = 10 % 3 // 1 (3 fits 3 times in 10, leaving 1)

For negative numbers:

swift
let negRemainder = -10 % 3 // -1

The sign of the second operand is ignored, so a % b and a % -b yield the same result.

Unary Operators

  • Unary Minus (-): Toggles a number’s sign:
    swift
    let value = 7
    let negativeValue = -value // -7
    let positiveValue = -negativeValue // 7
  • Unary Plus (+): Returns the value unchanged:
    swift
    let number = -5
    let unchanged = +number // -5

Compound Assignment Operators

Combine assignment with another operation:

swift
var score = 10
score += 5 // score is now 15 (same as score = score + 5)

Compound operators (e.g., +=, -=, *=, /=) don’t return values.

Comparison Operators

Compare values, returning a Bool:

  • Equal to (==)
  • Not equal to (!=)
  • Greater than (>)
  • Less than (<)
  • Greater than or equal to (>=)
  • Less than or equal to (<=)
swift
let a = 5, b = 3
print(a == b) // false
print(a != b) // true
print(a > b) // true
print(a < b) // false
print(a >= b) // true
print(a <= b) // false

Use in conditionals:

swift
let user = "Alice"
if user == "Alice" {
    print("Welcome, Alice!")
} else {
    print("Unknown user: \(user)")
}
// Prints: Welcome, Alice!

Compare tuples (same type, same number of elements):

swift
(2, "cat") < (3, "dog") // true (2 < 3, strings not compared)
(2, "cat") < (2, "dog") // true (2 == 2, "cat" < "dog")
(2, "cat") == (2, "cat") // true

Tuples with comparable elements (e.g., Int, String) can use <, >, etc., but not with Bool.

Ternary Conditional Operator

The ternary operator (condition ? value1 : value2) selects a value based on a condition:

swift
let temperature = 25
let fanSpeed = temperature > 20 ? 100 : 50 // fanSpeed is 100

Equivalent to:

swift
let fanSpeed: Int
if temperature > 20 {
    fanSpeed = 100
} else {
    fanSpeed = 50
}

Use sparingly to maintain readability.

Nil-Coalescing Operator

The nil-coalescing operator (??) unwraps an optional or provides a default:

swift
let defaultFont = "Arial"
var userFont: String? // nil
let fontToUse = userFont ?? defaultFont // fontToUse is "Arial"
userFont = "Helvetica"
let updatedFont = userFont ?? defaultFont // updatedFont is "Helvetica"

Equivalent to a != nil ? a! : b, but more concise. It uses short-circuit evaluation, skipping the default if the optional has a value.

Range Operators

Swift provides range operators for sequences of values.

Closed Range Operator

a...b includes a to b (inclusive):

swift
for i in 1...3 {
    print("Count: \(i)")
}
// Count: 1
// Count: 2
// Count: 3

Half-Open Range Operator

a..<b includes a up to, but not including, b:

swift
let colors = ["red", "blue", "green"]
for i in 0..<colors.count {
    print("Color \(i + 1): \(colors[i])")
}
// Color 1: red
// Color 2: blue
// Color 3: green

One-Sided Ranges

Omit one side for ranges extending indefinitely:

swift
for color in colors[1...] {
    print(color)
}
// blue
// green

for color in colors[...1] {
    print(color)
}
// red
// blue

Half-open one-sided range:

swift
for color in colors[..<2] {
    print(color)
}
// red
// blue

Check if a value is in a one-sided range:

swift
let range = ...10
print(range.contains(5)) // true
print(range.contains(15)) // false

Logical Operators

Logical operators manipulate Bool values:

  • Logical NOT (!)
  • Logical AND (&&)
  • Logical OR (||)

Logical NOT

Inverts a Bool:

swift
let isLocked = true
if !isLocked {
    print("Door is open")
} else {
    print("Door is locked")
}
// Prints: Door is locked

Logical AND

Requires both values to be true:

swift
let hasKey = true
let knowsCode = false
if hasKey && knowsCode {
    print("Access granted")
} else {
    print("Access denied")
}
// Prints: Access denied

Uses short-circuit evaluation: if the first value is false, the second isn’t evaluated.

Logical OR

Requires at least one true value:

swift
let hasPass = false
let isAdmin = true
if hasPass || isAdmin {
    print("Access granted")
} else {
    print("Access denied")
}
// Prints: Access granted

Uses short-circuit evaluation: if the first value is true, the second isn’t evaluated.

Combining Logical Operators

Combine operators with parentheses for clarity:

swift
let hasID = true
let hasToken = false
let isTrusted = true
if (hasID && hasToken) || isTrusted {
    print("Access granted")
} else {
    print("Access denied")
}
// Prints: Access granted

Logical operators are left-associative, evaluating left-to-right. Use parentheses to clarify complex expressions.

Released under the MIT License.