Swift While Loop

Swift's while and repeat-while loops let you repeat a block of code as long as a condition holds, giving you fine control over loops whose length isn't known in advance.

The while loop

A while loop evaluates a condition before each pass through the loop body. If the condition is true, the body runs and the condition is checked again; if it's false, the loop ends immediately. This makes while ideal for situations where the number of iterations depends on runtime data, such as reading input until a sentinel value appears or simulating a process until it settles.

Basic while loop

var countdown = 5

while countdown > 0 {
    print("T-minus \(countdown)")
    countdown -= 1
}

print("Liftoff!")

The repeat-while loop

Swift's repeat-while loop (known as do-while in many other languages) checks its condition after running the loop body, guaranteeing the body executes at least once. This is useful whenever the first pass must always happen, such as prompting a user at least once before validating their answer.

repeat-while executes at least once

var attempts = 0
var isCorrect = false

repeat {
    attempts += 1
    isCorrect = attempts == 3   // pretend the 3rd guess is right
    print("Attempt \(attempts): correct? \(isCorrect)")
} while !isCorrect

print("Solved after \(attempts) attempts")
Note: Choose repeat-while when the loop body must run before the condition makes sense to check, such as game loops that always render one frame first.

Controlling loops with break and continue

Inside any loop you can use break to exit immediately, or continue to skip the rest of the current iteration and jump back to the condition check. Combined with while, these keywords let you build loops that react to changing state mid-iteration rather than only at the top or bottom.

  • break exits the nearest enclosing loop entirely.
  • continue skips to the next condition check, bypassing remaining code in the body.
  • Labeled statements (e.g. outerLoop: while ...) let break/continue target an outer loop from within a nested one.
  • A while loop with a condition that never becomes false runs forever unless a break executes.

Using break and continue in a while loop

var number = 0

while number < 20 {
    number += 1
    if number % 2 != 0 {
        continue   // skip odd numbers
    }
    if number > 12 {
        break      // stop once we pass 12
    }
    print("Even number: \(number)")
}
Note: A while loop whose condition never changes inside the body will hang forever. Always make sure something in the loop body moves the condition toward false.

while vs repeat-while at a glance

Featurewhilerepeat-while
Condition checkedBefore the body runsAfter the body runs
Minimum executions01
Typical use caseLoop count unknown, may not run at allLoop must run once before checking anything
Note: Both loops accept any Boolean expression as their condition, including calls to functions that return Bool, so the exit condition can be as simple or as complex as your logic requires.

Exercise: Swift While Loop

When does a `while` loop check its condition?