๐ŸŽ“ A1Learner
๐Ÿ”

Swift While Loop

A while loop is a loop that runs its body again and again while a condition stays true. The condition gets a fresh check before every pass.

A counter ends the loop

The counter starts at 1 and grows by 1 on each pass. The check fails once the counter passes 3.

var count = 1
while count <= 3 {
    print(count)
    count += 1
}

A false first check skips the body

The counter starts past the limit the check allows. Only the final print shows, and the counter still holds its first value.

var count = 5
while count <= 3 {
    print(count)
    count += 1
}
print(count)

repeat-while runs once before its check

The condition is false from the start in this program. The counter still ends at 1, which shows the body ran exactly once.

var runs = 0
repeat {
    runs += 1
} while runs < 0
print(runs)

A while loop can build a total

Each pass adds the counter to a running total. The print after the loop shows the finished total.

var number = 1
var total = 0
while number <= 4 {
    total += number
    number += 1
}
print(total)

Example

var left = 3
while left > 0 {
    print(left)
    left -= 1
}
print(left)

Key points

  • The body runs again for as long as the check keeps passing.
  • The check sits after the word while in the loop line.
  • A counter changed inside the body can turn the check false and end the loop.
  • repeat-while places its check after the body instead of before it.
  • A while loop whose first check is false runs its body zero times.

In this example, the first line sets left to 3. The loop prints left and then lowers it by 1 on each pass, printing 3, 2 and 1. The check fails when left reaches 0, so the loop ends. The last line prints left and shows 0.

Note

A check that never turns false makes the loop run without end.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz Swift Compiler

Exercise

A repeat-while loop adds 1 to a counter that starts at 0. Its check is counter < 0. What does the counter hold after the loop?