Swift While Loop
A Swift while loop repeatedly executes a block of statements while its condition remains true. The condition is checked before every iteration, so the loop body may execute zero times when the condition is initially false.
Use a while loop when the number of iterations is not known in advance, such as reading values until valid input is received, processing items until a queue is empty, or repeating an operation until a state changes.
Swift While Loop Syntax and Execution Flow
The syntax of a Swift while loop is shown below.
while boolean_expression {
// set of statements
}
boolean_expression is evaluated and if it returns true, the set of statements inside the while block are executed. And then the condition is checked again. If it returns true, the statements are executed again. The process repeats until the boolean_expression evaluates to false.
- Swift evaluates the loop condition.
- If the condition is
true, Swift executes the statements inside the loop body. - Execution returns to the condition after the loop body finishes.
- The loop stops when the condition evaluates to
false.
The loop body should normally change a value used by the condition. Otherwise, the condition may never become false, resulting in an infinite loop.
Swift While Loop Example: Count from 0 to 4
Following example demonstrates the use of while loop to iterate a set of statements while i<5. Observe that we are modifying the state of the program by incrementing i in while block.
main.swift
var i = 0
while i < 5 {
print("i : \(i)")
i = i + 1
}
print("rest of the statements")
Output
$swift while_loop_example.swift
i : 0
i : 1
i : 2
i : 3
i : 4
rest of the statements
The variable i starts at 0. Each iteration prints its current value and increments it by one. When i becomes 5, the condition i < 5 is false and execution continues after the loop.
Swift While Loop Example When the Initial Condition Is False
Following example demonstrates while loop when the boolean expression evaluates to false in the first run.
main.swift
var i = 8
while i < 5 {
print("i : \(i)")
i = i + 1
}
print("rest of the statements")
Output
$swift while_loop_example.swift
rest of the statements
Because 8 < 5 is false at the first condition check, Swift skips the loop body. This pre-check behavior is the main difference between while and repeat-while.
Swift While Loop with a Decrementing Counter
A loop variable can move toward its stopping condition by decreasing instead of increasing. This example performs a countdown.
var count = 3
while count > 0 {
print(count)
count -= 1
}
print("Go")
Output
3
2
1
Go
Exit a Swift While Loop Early with Break
The break statement ends the nearest loop immediately, even when the loop condition is still true. It is useful when the stopping condition is discovered inside the loop body.
var number = 1
while number <= 10 {
if number == 4 {
break
}
print(number)
number += 1
}
print("Loop ended")
Output
1
2
3
Loop ended
When number becomes 4, break transfers execution to the first statement after the loop.
Skip a Swift While Loop Iteration with Continue
The continue statement skips the remaining statements in the current iteration and starts the next condition check. Update the loop variable before reaching continue so that the loop can still make progress.
var number = 0
while number < 5 {
number += 1
if number == 3 {
continue
}
print(number)
}
Output
1
2
4
5
The value 3 is not printed because that iteration reaches continue.
Swift While Loop Compared with Repeat-While
Swift provides two condition-controlled loops. A while loop checks its condition before the body, whereas a repeat-while loop checks the condition after the body.
| Loop | Condition check | Minimum executions |
|---|---|---|
while | Before the loop body | Zero |
repeat-while | After the loop body | One |
The syntax of repeat-while, called a do-while loop in some other languages, is:
repeat {
// statements
} while condition
In the following comparison, the starting condition is false. The while body does not run, but the repeat-while body runs once before checking the condition.
var firstValue = 5
while firstValue < 5 {
print("while: \(firstValue)")
firstValue += 1
}
var secondValue = 5
repeat {
print("repeat-while: \(secondValue)")
secondValue += 1
} while secondValue < 5
Output
repeat-while: 5
When to Use While Instead of For-In in Swift
Choose the loop based on what controls repetition:
- Use
whilewhen repetition depends on a changing condition and the number of iterations is not known beforehand. - Use
repeat-whilewhen the body must execute at least once before the condition is tested. - Use
for-inwhen iterating through a range, array, string, dictionary, or another sequence.
For example, counting from 1 through 10 is usually clearer with for number in 1...10, while retrying an operation until it succeeds is naturally expressed with while.
Common Swift While Loop Mistakes
- Not updating the condition state: A condition that never changes can create an infinite loop.
- Updating in the wrong direction: Incrementing a variable when the condition requires it to decrease may prevent termination.
- Placing the update after
continue: The update may be skipped, causing the same condition to repeat indefinitely. - Using
whilefor a known sequence: Afor-inloop is often shorter and less error-prone for ranges and collections. - Forgetting boundary cases: Check how the loop behaves when the condition is false before the first iteration.
Swift While Loop Review Checklist
- Confirm that the condition is a Boolean expression.
- Verify that the loop body changes the state used by the condition.
- Test the case in which the initial condition is already false.
- Check every
continuepath to ensure the loop still advances. - Confirm that
breakexits the intended loop, especially in nested control flow.
Swift While Loop FAQs
Can a Swift while loop execute zero times?
Yes. Swift checks the condition before entering the loop body. If the condition is initially false, the body is skipped.
How do I stop a while loop in Swift?
Make the loop condition become false through normal state changes, or use break to exit the loop immediately.
What is the Swift equivalent of a do-while loop?
Swift uses repeat-while. Its body executes once before Swift evaluates the condition.
How can I prevent an infinite while loop in Swift?
Ensure that each iteration moves the program toward a false condition. Also review branches containing continue, because they can skip an update placed later in the loop body.
Summary of Swift While Loop Behavior
A Swift while loop checks its condition before each iteration and repeats until that condition is false. Use break for an early exit, continue to skip the remainder of an iteration, and repeat-while when the body must run at least once. The official Swift Control Flow documentation covers these loop and control-transfer statements in the language guide.
In this Swift Tutorial, we have learned about Swift While Loop with syntax and examples covering different scenarios.
TutorialKart.com