Swift while Loop: Syntax, Examples, and Common Mistakes

The Swift while loop is one of the simplest ways to repeat code as long as a condition stays true. It is useful when you do not know in advance how many times something should run, such as reading input, counting down, retrying work, or processing values until a limit is reached. In this article, you will learn how the Swift while loop works, how to write it correctly, when to use it instead of other loop types, and how to avoid the mistakes that often cause bugs or infinite loops.

Quick answer: In Swift, a while loop checks its condition before each iteration. If the condition is true, the loop body runs; if it is false, the loop stops immediately. Use while when repetition depends on a changing condition rather than a fixed range of values.

Difficulty: Beginner

Helpful to know first: You'll understand this better if you know basic Swift syntax, Boolean conditions, variables, and simple operators like <, >, and ==.

1. What Is while?

A while loop is a control-flow statement that repeats a block of code while a condition remains true. Swift evaluates the condition first, before each pass through the loop body.

Think of while as saying: “Keep doing this as long as this condition is still true.”

2. Why while Matters

Not every repeating task fits neatly into a for-in loop. Sometimes you are not looping over a collection or a fixed range. Instead, you want to keep going until something changes.

That is where while is helpful. Common examples include:

You should use while when the stopping rule matters more than the exact number of iterations. If you already know the exact values or range to loop over, for-in is often clearer.

3. Basic Syntax or Core Idea

The basic Swift syntax for a while loop is short and readable.

Basic structure

The condition goes after the while keyword, and the repeated code goes inside braces.

var count = 1

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

This loop prints the numbers 1 through 3. Each time the loop runs, Swift checks whether count <= 3 is true. After printing, the code increases count by 1 so the loop can eventually stop.

How execution flows

The loop follows this sequence:

A while loop usually needs code inside it that changes the condition. Without that change, the loop may never end.

4. Step-by-Step Examples

Example 1: Counting upward

This is the classic beginner example. It shows how a variable changes until the condition becomes false.

var number = 1

while number <= 5 {
    print("Number: \(number)")
    number += 1
}

This prints five lines, from 1 to 5. The important detail is the increment at the end, which moves the loop toward stopping.

Example 2: Countdown

A while loop can also count backward.

var seconds = 3

while seconds > 0 {
    print("\(seconds)...")
    seconds -= 1
}

print("Go!")

The loop runs while seconds > 0. Once seconds becomes 0, the condition is false, so the loop ends and the final print statement runs.

Example 3: Processing an array with an index

Although Swift often prefers for-in for arrays, a while loop can still be useful when you need manual index control.

let names = ["Ana", "Ben", "Chris"]
var index = 0

while index < names.count {
    print("Hello, \(names[index])")
    index += 1
}

This loop keeps going as long as the index is within the array bounds. It demonstrates a common pattern: start at 0, check against count, then move to the next index.

Example 4: Repeating until a target is reached

This example simulates accumulating points until a goal is met.

var score = 0

while score < 20 {
    score += 5
    print("Current score: \(score)")
}

The loop does not care about a fixed number of iterations. It only cares whether the goal has been reached yet.

5. Practical Use Cases

In day-to-day Swift code, while is especially useful when the stopping rule is based on state that changes over time.

6. Common Mistakes

Mistake 1: Forgetting to change the loop variable

A while loop usually depends on a variable changing during each iteration. If nothing changes, the condition may stay true forever.

Problem: This code creates an infinite loop because count never changes, so the condition never becomes false.

var count = 1

while count <= 3 {
    print(count)
}

Fix: Update the variable inside the loop so the condition can eventually become false.

var count = 1

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

The corrected version works because each iteration moves the loop one step closer to stopping.

Mistake 2: Using let for a value that must change

Values declared with let are constants in Swift. A loop counter or condition-related variable often needs to be reassigned.

Problem: This code tries to change a constant, so Swift reports an error similar to Left side of mutating operator isn't mutable: 'count' is a 'let' constant.

let count = 1

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

Fix: Use var when the value needs to change during the loop.

var count = 1

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

The corrected version works because var allows reassignment as the loop progresses.

Mistake 3: Going out of bounds with an array index

When using while to access an array by index, your condition must stop before the index reaches an invalid position.

Problem: This code uses <= with names.count, which allows the index to become equal to the array size. That causes a runtime crash with an index out of range error.

let names = ["Ana", "Ben", "Chris"]
var index = 0

while index <= names.count {
    print(names[index])
    index += 1
}

Fix: Use < so the last valid index is accessed safely.

let names = ["Ana", "Ben", "Chris"]
var index = 0

while index < names.count {
    print(names[index])
    index += 1
}

The corrected version works because valid array indexes go from 0 up to, but not including, count.

Mistake 4: Using while when you need at least one run

Beginners sometimes expect a while loop to run once even when the condition is false at the start. That is not how it works.

Problem: This code prints nothing because the condition is checked before the first iteration, and it is already false.

var attempts = 5

while attempts < 3 {
    print("Trying...")
    attempts += 1
}

Fix: Use repeat-while if the code must run once before the condition is checked.

var attempts = 5

repeat {
    print("Trying...")
    attempts += 1
} while attempts < 3

The corrected version works because repeat-while executes the body before checking the condition.

7. Best Practices

Practice 1: Make the stopping condition obvious

A clear condition makes loops easier to read and safer to maintain.

Less clear:

var x = 0

while x != 10 {
    x += 1
}

Preferred:

var x = 0

while x < 10 {
    x += 1
}

The preferred version expresses the boundary directly, which makes the loop intent easier to understand.

Practice 2: Prefer for-in for fixed ranges

If you already know the exact range, for-in is often simpler and less error-prone than a manual while loop.

Less preferred:

var i = 1

while i <= 5 {
    print(i)
    i += 1
}

Preferred:

for i in 1...5 {
    print(i)
}

The preferred version avoids manual counter management, so there is less chance of forgetting an increment or writing the wrong condition.

Practice 3: Keep loop state small and focused

The more variables a loop controls at once, the harder it becomes to reason about. Use only the state you actually need.

Less preferred:

var index = 0
var total = 0
var unusedFlag = true
let values = [2, 4, 6]

while index < values.count {
    total += values[index]
    index += 1
}

Preferred:

var index = 0
var total = 0
let values = [2, 4, 6]

while index < values.count {
    total += values[index]
    index += 1
}

The preferred version is easier to follow because every variable has a clear purpose in the loop.

8. Limitations and Edge Cases

One common “not working” scenario is when a beginner expects output from a loop, but the condition is already false before the first iteration. Another is when the program seems stuck because the condition never becomes false.

9. Practical Mini Project

Here is a small but complete example that uses a while loop to simulate retrying a login until the correct PIN is entered or the maximum number of attempts is reached.

let correctPIN = "2468"
let enteredPINs = ["1111", "1357", "2468"]

var attempt = 0
var isUnlocked = false

while attempt < enteredPINs.count && !isUnlocked {
    let currentPIN = enteredPINs[attempt]
    print("Attempt \(attempt + 1): \(currentPIN)")

    if currentPIN == correctPIN {
        isUnlocked = true
        print("Unlocked")
    } else {
        print("Incorrect PIN")
    }

    attempt += 1
}

if !isUnlocked {
    print("Access denied")
}

This mini project shows a realistic use of while. The loop continues only while there are attempts left and the PIN has not been matched yet. It demonstrates that while is often about combining conditions to control repeated work safely.

10. Key Points

11. Practice Exercise

Try this exercise to check that you understand how a while loop controls repetition.

Expected output:

2
4
6
8
10
Done

Hint: Start with var value = 2 and make sure the loop changes value each time.

var value = 2

while value <= 10 {
    print(value)
    value += 2
}

print("Done")

12. Final Summary

The Swift while loop is a simple but important control-flow tool. It repeats code only while a condition is true, which makes it a good choice when you do not know the exact number of iterations ahead of time. You saw the core syntax, how execution flows, and several practical examples including counters, countdowns, array processing, and condition-based repetition.

You also saw the mistakes that matter most in real Swift code: forgetting to update the loop state, using let when a value needs to change, creating off-by-one array errors, and choosing while when repeat-while is the correct fit. If you want a strong next step, learn how Swift for-in, break, and continue work so you can choose the right loop structure for each situation.