- API fetch
- Array
- Async await
- Class
- Closures
- Computed property
- Concurrency
- Constants
- Data types
- Defer statement
- Dictionary
- Enum
- Escaping closure
- Extension
- For loop
- forEach
- Function
- Generics
- Guard statement
- if let statement
- Inheritance
- inout
- Lazy var
- Operator
- Optionals
- Property observers
- Property wrapper
- Protocol
- String formatting
- String interpolation
- Struct
- Switch statement
- Try catch
- Tuple
- Variables
- While loop
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
.
Standard While Loop
while condition {
// Code executes as long as condition is true
}
condition
must be a Boolean expression.- The loop runs only if the condition is true before entering the block.
Example:
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.
repeat {
// Code runs at least once
} while condition
Example:
var attempts = 1
repeat {
print("Attempt \(attempts)")
attempts += 1
} while attempts <= 3
When to Use While Loops
1. Waiting for a Condition to Change
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
var input: String? = nil
while input != "yes" {
print("Type 'yes' to continue:")
input = readLine()
}
Perfect when waiting for specific input.
3. Simulating Processes
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
var balance = 50
while balance > 0 {
print("Current balance: \(balance)")
balance -= 10
}
Infinite Loop With Break
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
var pin = ""
repeat {
print("Enter your PIN:")
pin = readLine() ?? ""
} while pin != "1234"
print("Access granted.")
Advanced Usage
Nested Loops
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
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)")
}
break
exits the loop entirely.continue
skips the current iteration.
Looping Through Optionals
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
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
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.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.