# Swift repeat-while Loop: Syntax, Examples, and Best Uses

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

The Swift `repeat-while` loop is a control-flow statement that runs a block of code first and checks its condition afterward. That small difference makes it useful when your code must execute at least once before deciding whether to continue. In this guide, you will learn the syntax, how it compares to `while`, where it is useful in real code, and how to avoid common mistakes.

> **Quick answer:** Use a Swift `repeat-while` loop when you want the loop body to run at least one time before the condition is tested. It is similar to a `while` loop, but the condition appears at the end instead of the beginning.

> **Difficulty:** Beginner
>
> **Helpful to know first:** You'll understand this better if you know basic Swift syntax, Boolean conditions, variables, and how ordinary `while` loops work.

## 1. What Is repeat-while?

A `repeat-while` loop is a Swift loop that always runs its body once before checking whether it should continue.

- It is part of Swift control flow.
- The loop condition is checked after the code block runs.
- It guarantees at least one execution of the loop body.
- It is useful when the first pass must happen before any decision can be made.
- It is often compared with `while`, which checks the condition before running the body.

If you have used other languages, you may have seen a `do-while` loop. In Swift, the equivalent idea is spelled `repeat-while`.

## 2. Why repeat-while Matters

Most loops are about repetition, but not all repetition starts in the same way. Sometimes you need one pass through the code before you can decide whether another pass is necessary.

That is where `repeat-while` helps. It is especially useful when:

- You need to ask for input at least once.
- You are running a menu until the user chooses to exit.
- You are retrying an operation and want the first attempt to happen immediately.
- You need one initial calculation before evaluating a stop condition.

If the code should possibly run zero times, a regular `while` loop is usually the better choice. If the code must run once no matter what, `repeat-while` is often clearer.

## 3. Basic Syntax

### Basic structure

The syntax starts with `repeat`, then a block of code, and finally a `while` condition.

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

Output (tested with Swift 6.4):

```text
1
2
3
```

This loop prints the current value, then increases it, and only then checks whether the loop should continue.

The output is:

```swift
1
2
3
```

### How it differs from while

With `while`, the condition is tested first. With `repeat-while`, the condition is tested after the loop body runs.

```swift
var value = 5

repeat {
    print("This runs once")
} while value < 3
```

Output (tested with Swift 6.4):

```text
This runs once
```

Even though `value < 3` is false, the message still prints once because the check happens at the end.

## 4. Step-by-Step Examples

### Example 1: Counting numbers

This is the simplest way to see how the loop works.

```swift
var number = 1

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

Output (tested with Swift 6.4):

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

The loop starts at 1, prints it, increments it, and keeps going until the condition becomes false. This shows the normal structure of update, then test.

### Example 2: A loop that runs once even when the condition is false

This example demonstrates the main behavior that makes `repeat-while` different from `while`.

```swift
var score = 100

repeat {
    print("Checking score")
} while score < 50
```

Output (tested with Swift 6.4):

```text
Checking score
```

The message prints once, even though the condition is false from the beginning. That is expected behavior, not a bug.

### Example 3: Menu-style repetition

A menu is a common case where you want to show choices first and then decide whether to repeat.

```swift
var choice = ""

repeat {
    print("Menu:")
    print("1. View Profile")
    print("2. Settings")
    print("Type quit to exit")

    // Imagine choice comes from user input
    choice = "quit"
} while choice != "quit"
```

Output (tested with Swift 6.4):

```text
Menu:
1. View Profile
2. Settings
Type quit to exit
```

This pattern makes sense because the menu should be shown at least once before the user has a chance to exit.

### Example 4: Retrying until success

Sometimes you want to attempt something immediately and keep trying until it succeeds.

```swift
var attempt = 1
var didConnect = false

repeat {
    print("Connection attempt \(attempt)")

    if attempt == 3 {
        didConnect = true
    }

    attempt += 1
} while !didConnect && attempt <= 5

print("Connected: \(didConnect)")
```

Output (tested with Swift 6.4):

```text
Connection attempt 1
Connection attempt 2
Connection attempt 3
Connected: true
```

The first connection attempt happens right away, which is often what you want in retry logic.

## 5. Practical Use Cases

- Showing a command-line menu before checking whether the user wants to continue.
- Prompting for input where at least one prompt must appear.
- Retrying a network-like operation in example code or simulations.
- Running validation logic once before deciding if another pass is needed.
- Processing game turns or rounds when the first round should always begin.
- Repeating calculations until a threshold is reached, after the first calculation is performed.

## 6. Common Mistakes

### Mistake 1: Using repeat-while when the loop should possibly run zero times

Beginners sometimes choose `repeat-while` without realizing that it always executes once. That can produce unexpected output or state changes.

**Problem:** This code prints a value even though the condition is false at the start. If zero executions are allowed, `repeat-while` is the wrong loop.

```swift
var temperature = 25

repeat {
    print("Too cold")
} while temperature < 20
```

Output (tested with Swift 6.4):

```text
Too cold
```

**Fix:** Use `while` when the loop might need to skip execution entirely.

```swift
var temperature = 25

while temperature < 20 {
    print("Too cold")
}
```

The corrected version works because the condition is checked before any code runs.

### Mistake 2: Forgetting to update the loop variable

A `repeat-while` loop usually needs some value to change inside the loop. If nothing changes, the condition may remain true forever.

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

```swift
var count = 1

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

**Fix:** Update the value that controls the condition so the loop can eventually stop.

```swift
var count = 1

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

Output (tested with Swift 6.4):

```text
1
2
3
```

The corrected version works because the loop moves toward a false condition on each iteration.

### Mistake 3: Using a constant for a value that must change

If the loop depends on a changing value, that value cannot be declared with `let`. Swift constants cannot be reassigned.

**Problem:** This code tries to change a constant, so Swift produces a compile-time error such as `Left side of mutating operator isn't mutable: 'count' is a 'let' constant`.

```swift
let count = 1

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

**Fix:** Declare the variable with `var` if it needs to change during the loop.

```swift
var count = 1

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

Output (tested with Swift 6.4):

```text
1
2
3
```

The corrected version works because `var` allows the loop control value to be updated.

## 7. Best Practices

### Choose repeat-while only when one execution is guaranteed to make sense

The main reason to use `repeat-while` is clarity. If the first execution is always required, it expresses that intention directly.

```swift
// Less clear for guaranteed first execution
var attempt = 1
var success = false

while !success && attempt <= 3 {
    success = attempt == 1
    attempt += 1
}
```

```swift
// Clearer when the first attempt must happen
var attempt = 1
var success = false

repeat {
    success = attempt == 1
    attempt += 1
} while !success && attempt <= 3
```

The second version better matches the intent of “try once, then keep going if needed.”

### Keep the stopping condition easy to read

Complex loop conditions are harder to debug. A simple condition makes the loop easier to understand and maintain.

```swift
// Harder to scan quickly
repeat {
    // work
} while !isFinished && !hasError && attempts < 5
```

```swift
// Clearer with named meaning
var shouldContinue = true

repeat {
    // work
    shouldContinue = !isFinished && !hasError && attempts < 5
} while shouldContinue
```

This approach can make loop logic easier to reason about, especially as conditions become more involved.

### Prefer for-in when iterating over known collections or ranges

`repeat-while` is not the best loop for every job. If you are looping through a range or collection, `for-in` is usually safer and more expressive.

```swift
// Less preferred for a fixed range
var index = 1

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

Output (tested with Swift 6.4):

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

```swift
// Preferred for a fixed range
for index in 1...5 {
    print(index)
}
```

Output (tested with Swift 6.4):

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

The `for-in` version is shorter and avoids manual updates to the counter.

## 8. Limitations and Edge Cases

- `repeat-while` always runs once, even when the condition is false immediately.
- It can create infinite loops if the state needed for the condition never changes.
- It is usually less ideal than `for-in` for iterating over arrays, dictionaries, or numeric ranges.
- If the loop body contains early exits like `break` or `continue`, the flow can become harder for beginners to follow.
- Very complex conditions at the end of the loop can reduce readability because the stop logic is separated from the start of the block.
- A common “not working” situation is expecting the loop to skip entirely when the condition starts false. That is normal behavior for this loop type.

## 9. Practical Mini Project

Here is a small, complete example that simulates a password prompt. The program gives the user repeated attempts and stops when the password is correct or the maximum number of tries is reached.

```swift
let correctPassword = "swift123"
var attempts = 0
var enteredPassword = ""
let maxAttempts = 3

repeat {
    attempts += 1
    print("Attempt \(attempts) of \(maxAttempts)")

    // Simulated user input for example purposes
    if attempts == 3 {
        enteredPassword = "swift123"
    } else {
        enteredPassword = "wrong"
    }

    if enteredPassword == correctPassword {
        print("Access granted")
    } else {
        print("Incorrect password")
    }
} while enteredPassword != correctPassword && attempts < maxAttempts
```

Output (tested with Swift 6.4):

```text
Attempt 1 of 3
Incorrect password
Attempt 2 of 3
Incorrect password
Attempt 3 of 3
Access granted
```

This is a good fit for `repeat-while` because at least one password attempt must happen. The loop body performs the attempt, then the condition checks whether another attempt is allowed.

## 10. Key Points

- `repeat-while` runs the loop body before testing the condition.
- It guarantees at least one execution.
- Use it when the first pass must happen before you know whether to continue.
- Use `while` instead if the loop may need to run zero times.
- Always update the loop state so the condition can eventually become false.
- For fixed ranges and collections, `for-in` is often a better choice.

## 11. Practice Exercise

Try this exercise to test your understanding.

- Create a variable named `value` starting at `1`.
- Use a `repeat-while` loop to print the square of each value.
- Keep looping until `value` becomes greater than `4`.
- Increase `value` inside the loop.

**Expected output:**

```swift
1
4
9
16
```

**Hint:** Print `value * value` before increasing `value`.

```swift
var value = 1

repeat {
    print(value * value)
    value += 1
} while value <= 4
```

Output (tested with Swift 6.4):

```text
1
4
9
16
```

## 12. Final Summary

The Swift `repeat-while` loop is a simple but important control-flow tool. Its defining feature is that the code runs first and the condition is checked afterward. That makes it a strong choice for tasks like menus, prompts, retries, and any other situation where one execution must happen before you can decide whether to continue.

The most important thing to remember is the difference between `repeat-while` and `while`. If zero executions are possible, use `while`. If one execution is guaranteed and meaningful, `repeat-while` can make your intent clearer. As a next step, compare it with Swift `while` and `for-in` loops so you can choose the right loop for each situation.
