# Swift while Loop: Syntax, Examples, and Common Mistakes

Source: https://devdocs10.com/articles/swift/swift-while  
By Murat Bo · Published 2026-05-12 · DevDocs10 (https://devdocs10.com)

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.

- It is a *pre-test* loop, which means the condition is checked before the code inside runs.
- If the condition is false at the start, the loop body runs zero times.
- It is useful when the number of iterations is not known ahead of time.
- It usually depends on one or more variables changing inside the loop.
- It is different from `repeat-while`, which runs the loop body once before checking the condition.

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:

- Counting down until a value reaches zero
- Repeating a task until user input becomes valid
- Searching until a condition is met
- Retrying an operation until it succeeds or reaches a limit
- Processing data until there is nothing left to process

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

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.

```swift
var count = 1

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

Output (tested with Swift 6.4):

```text
1
2
3
```

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:

- Check the condition.
- If it is true, run the loop body.
- Return to the condition and check again.
- Stop when the condition becomes false.

> 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.

```swift
var number = 1

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

Output (tested with Swift 6.4):

```text
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
```

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.

```swift
var seconds = 3

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

print("Go!")
```

Output (tested with Swift 6.4):

```text
3...
2...
1...
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.

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

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

Output (tested with Swift 6.4):

```text
Hello, Ana
Hello, Ben
Hello, Chris
```

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.

```swift
var score = 0

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

Output (tested with Swift 6.4):

```text
Current score: 5
Current score: 10
Current score: 15
Current score: 20
```

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

- Retrying a request or task until it succeeds or hits a retry limit
- Reading characters or tokens until the end of available input
- Running a game loop while the player is still active
- Checking conditions repeatedly until data becomes valid
- Walking through a collection manually when you need flexible index control
- Continuing calculations until a threshold is reached

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.

```swift
var count = 1

while count <= 3 {
    print(count)
}
```

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

```swift
var count = 1

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

Output (tested with Swift 6.4):

```text
1
2
3
```

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`.

```swift
let count = 1

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

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

```swift
var count = 1

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

Output (tested with Swift 6.4):

```text
1
2
3
```

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.

```swift
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.

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

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

Output (tested with Swift 6.4):

```text
Ana
Ben
Chris
```

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.

```swift
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.

```swift
var attempts = 5

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

Output (tested with Swift 6.4):

```text
Trying...
```

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:

```swift
var x = 0

while x != 10 {
    x += 1
}
```

Preferred:

```swift
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:

```swift
var i = 1

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

Output (tested with Swift 6.4):

```text
1
2
3
4
5
```

Preferred:

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

Output (tested with Swift 6.4):

```text
1
2
3
4
5
```

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:

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

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

Preferred:

```swift
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

- If the condition is false at the start, the loop body does not run at all.
- A `while true` loop is valid Swift, but it will run forever unless you break out of it with logic such as `break` or `return`.
- Manual index-based loops are more error-prone than `for-in` loops because they can cause off-by-one mistakes.
- If the loop condition depends on external state that never changes, the loop may appear to hang.
- Very large or infinite loops can make command-line programs seem frozen and can block progress if they do too much work without stopping.
- Using floating-point values in loop conditions can be tricky because decimal values are not always represented exactly in memory.

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.

```swift
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")
}
```

Output (tested with Swift 6.4):

```text
Attempt 1: 1111
Incorrect PIN
Attempt 2: 1357
Incorrect PIN
Attempt 3: 2468
Unlocked
```

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

- `while` repeats code as long as its condition is true.
- Swift checks the condition before each iteration.
- If the condition starts false, the loop body runs zero times.
- Use `while` when the number of iterations is not known in advance.
- Make sure something inside the loop can eventually make the condition false.
- Use `var` for values that must change during the loop.
- Be careful with array indexes to avoid index out of range crashes.
- Use `repeat-while` instead when the code must run at least once.

## 11. Practice Exercise

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

- Create a variable named `value` starting at 2.
- Use a `while` loop to print the value while it is less than or equal to 10.
- Increase the value by 2 during each iteration.
- After the loop, print `"Done"`.

**Expected output:**

```swift
2
4
6
8
10
Done
```

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

```swift
var value = 2

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

print("Done")
```

Output (tested with Swift 6.4):

```text
2
4
6
8
10
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.
