SWIFT
Swift While Loop: Syntax, Usage, and Examples
A while loop in Swift repeatedly runs a block of code as long as a condition remains true. It’s ideal when the number of iterations isn’t known in advance and depends on changing runtime values.
Basic Syntax
Swift offers two loop types: while and repeat-while.
Learn Swift on Mimo
Standard While Loop
Swift
while condition {
// Code executes as long as condition is true
}
conditionmust be a Boolean expression.- The loop runs only if the condition is true before entering the block.
Example:
Swift
var counter = 3
while counter > 0 {
print("Countdown: \(counter)")
counter -= 1
}
This prints from 3 down to 1, then exits.
Repeat-While Loop
Swift doesn’t have a do while keyword, but the repeat-while structure behaves the same: it runs once before checking the condition.
Swift
repeat {
// Code runs at least once
} while condition
Example:
Swift
var attempts = 1
repeat {
print("Attempt \(attempts)")
attempts += 1
} while attempts <= 3
When to Use While Loops
1. Waiting for a Condition to Change
Swift
var isConnected = false
var retries = 0
while !isConnected && retries < 5 {
print("Trying to connect...")
retries += 1
}
Useful for polling or retry logic.
2. Validating User Input
Swift
var input: String? = nil
while input != "yes" {
print("Type 'yes' to continue:")
input = readLine()
}
Perfect when waiting for specific input.
3. Simulating Processes
Swift
var temperature = 100.0
while temperature > 37.0 {
print("Cooling down... Temp: \(temperature)")
temperature -= 5.0
}
Use when simulating changing state.
Practical Examples
Loop Until a Condition Fails
Swift
var balance = 50
while balance > 0 {
print("Current balance: \(balance)")
balance -= 10
}
Infinite Loop With Break
Swift
var counter = 0
while true {
if counter == 5 {
break
}
print("Counter is \(counter)")
counter += 1
}
Infinite loops are valid but require a reliable exit condition.
Repeat-While for Guaranteed Execution
Swift
var pin = ""
repeat {
print("Enter your PIN:")
pin = readLine() ?? ""
} while pin != "1234"
print("Access granted.")
Advanced Usage
Nested Loops
Swift
var i = 1
while i <= 3 {
var j = 1
repeat {
print("Pair: (\(i), \(j))")
j += 1
} while j <= 2
i += 1
}
You can freely combine while and repeat-while loops.
Using Break and Continue
Swift
let numbers = [1, 2, 3, 4, 5]
var index = 0
while index < numbers.count {
let value = numbers[index]
index += 1
if value % 2 == 0 {
continue // Skip even numbers
}
print("Odd number: \(value)")
}
breakexits the loop entirely.continueskips the current iteration.
Looping Through Optionals
Swift
let optionalNames: [String?] = ["Ana", nil, "Leo", nil, "Kai"]
var i = 0
while i < optionalNames.count {
if let name = optionalNames[i] {
print("Name: \(name)")
}
i += 1
}
This pattern helps with safely unwrapping values during iteration.
Avoiding Infinite Loops
Swift
var i = 0
while i < 3 {
print(i)
// i += 1 // Don't forget to increment!
}
Make sure your loop variable updates, or the loop may never end.
Best Practices with Repeat-While
- Use when code must run at least once (e.g., login prompts).
- Keep conditions simple and expressive.
- Avoid changing multiple variables inside the loop unless needed.
Looping Over Collections with Indexes
Swift
let colors = ["red", "green", "blue"]
var i = 0
while i < colors.count {
print("Color: \(colors[i])")
i += 1
}
This gives more control than a for-in loop—useful for skipping or jumping.
Summary
Swift’s while loop is perfect for situations where you can’t predict how many times to repeat a task. It’s useful for input validation, polling, simulations, or retry logic. When at least one execution is required, repeat-while ensures the loop runs once before checking the condition.
Compared to for-in, while gives more flexibility but also requires you to manage conditions, indices, and loop state carefully. With control tools like break, continue, and optional unwrapping, while remains one of the most powerful loop constructs in Swift.
Join 35M+ people learning for free on Mimo
4.8 out of 5 across 1M+ reviews
Check us out on Apple AppStore, Google Play Store, and Trustpilot