Skip to content

Control Flow

Swift provides several ways to control the flow of execution, including conditionals and loops.

Syntax Rules

Across all control flow structures in Swift:

  • Braces {}: Braces are mandatory for all blocks (if, for, while, switch, etc.), including single-line blocks.
  • Parentheses (): Parentheses are optional and usually omitted for all conditions (like in if or while).
  • Semicolons ;: Semicolons are optional (at the end of statements) everywhere in Swift, unless you're packing multiple statements onto one line.

Conditionals

If Statement

Standard if, else if, and else blocks.

swift
let score = 85

if score >= 90 {
    print("Grade: A")
} else if score >= 80 {
    print("Grade: B")
} else {
    print("Grade: C")
}

Switch Statement

Swift switch statements are powerful and must be exhaustive (covering all possibilities or using a default case).

  • No Implicit Fallthrough: Swift automatically exits the switch once a match is found. You don't need to write break at the end of every case.
  • Flexible Matching: Cases can match multiple values (separated by commas), tuples, and ranges (e.g., 1...3 for numbers 1 through 3).
swift
let count = 5

switch count {
case 0:
    print("None")
case 1...3: // Range matching
    print("A few")
case 4, 5, 6: // Multiple value matching
    print("Several")
default:
    print("Many")
}

Loops

For-In Loop

Used to iterate over ranges, arrays, dictionaries, or sets.

swift
// Iterate over a range
for i in 1...5 {
    print(i) // 1, 2, 3, 4, 5
}

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

While Loops

  • while: Evaluates the condition before each pass.
  • repeat-while: Evaluates the condition after each pass (guarantees at least one execution).
swift
var count = 5
while count > 0 {
    print(count)
    count -= 1
}

repeat {
    print("Executed once")
} while false

Control Transfer

  • break: Ends the loop immediately.
  • continue: Skips to the next iteration of the loop.