- 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
The Swift while loop
is a fundamental control flow structure that repeatedly executes a block of code as long as a given condition remains true. It’s ideal for situations where the number of iterations isn’t known in advance and depends on changing conditions during runtime.
How to Use a Swift While Loop
There are two primary forms of the while loop Swift
provides:
Basic While Loop Syntax
while condition {
// Code to execute as long as condition is true
}
condition
is a Boolean expression.- The loop body runs only if the condition is true at the start of each iteration.
Example:
var counter = 3
while counter > 0 {
print("Countdown: \(counter)")
counter -= 1
}
This prints a countdown from 3 to 1 and stops when counter
becomes 0.
Repeat-While Loop Syntax (Do-While Equivalent)
Swift doesn’t have a keyword do while loop
, but it supports the same functionality using repeat while
. This guarantees that the loop body runs at least once, even if the condition is false initially.
repeat {
// Code to run at least once
} while condition
Example:
var attempts = 1
repeat {
print("Attempt \(attempts)")
attempts += 1
} while attempts <= 3
When to Use the While Loop Swift
A while loop in Swift
is the right choice when the condition that controls the loop isn’t based on a known range or sequence. Here are common scenarios where the Swift while loop excels:
1. Waiting for External Conditions
Use it when your code needs to pause or wait for a specific condition to change—like a network response or hardware input.
var isConnected = false
var retries = 0
while !isConnected && retries < 5 {
print("Trying to connect...")
// Simulate a failed connection attempt
retries += 1
}
2. User Input Validation
Use a while loop to repeatedly prompt users for input until they enter a valid response.
var input: String? = nil
while input != "yes" {
print("Type 'yes' to continue:")
input = readLine()
}
3. Simulating or Repeating a Process
When you want to run a simulation, retry a process, or animate something with flexible stopping conditions, the while loop Swift
approach offers great control.
var temperature = 100.0
while temperature > 37.0 {
print("Cooling down... Temp: \(temperature)")
temperature -= 5.0
}
Examples of While Loop Swift
Example 1: Loop Until a Condition Fails
var balance = 50
while balance > 0 {
print("Current balance: \(balance)")
balance -= 10
}
This loop reduces the balance in steps of 10 and stops at 0.
Example 2: Infinite Loop With Break
var counter = 0
while true {
if counter == 5 {
break // Exit when counter hits 5
}
print("Counter is \(counter)")
counter += 1
}
Use infinite loops with care. They’re often used in game loops, service daemons, or reactive listeners, but always require a reliable exit condition.
Example 3: Repeat-While for Guaranteed Execution
var pin: String = ""
repeat {
print("Enter your PIN:")
pin = readLine() ?? ""
} while pin != "1234"
print("Access granted.")
Even if the initial value of pin
is already "1234", the loop runs at least once.
Learn More About the While Loop in Swift
Nesting Loops
You can nest while
or repeat while
loops when working with multidimensional data or layered logic:
var i = 1
while i <= 3 {
var j = 1
repeat {
print("Pair: (\(i), \(j))")
j += 1
} while j <= 2
i += 1
}
Using Break and Continue
The break
statement exits the loop immediately. The continue
statement skips the current iteration and jumps to the next one.
var 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 and continue are essential for controlling loop flow more precisely.
Using While Loop with Optionals
A while loop can be used to unwrap optionals conditionally.
var optionalNames: [String?] = ["Ana", nil, "Leo", nil, "Kai"]
var index = 0
while index < optionalNames.count {
if let name = optionalNames[index] {
print("Name: \(name)")
}
index += 1
}
This is useful when parsing optional values in a data structure.
Avoiding Infinite Loops
A common mistake is forgetting to change the loop condition variable, leading to an infinite loop.
var i = 0
while i < 3 {
print(i)
// i += 1 missing here would cause an infinite loop
}
Always double-check that your loop will eventually terminate unless you explicitly want it to run indefinitely.
Repeat While Loop Swift Best Practices
- Keep the loop condition readable.
- Don’t mutate multiple loop variables unless necessary.
- Prefer
repeat while
when the loop should always run at least once, like prompting for credentials or initiating a process.
Using While with Collections
Although for-in
loops are often better for iterating over collections, you can still use a while loop Swift
approach with an index for more control.
let colors = ["red", "green", "blue"]
var i = 0
while i < colors.count {
print("Color: \(colors[i])")
i += 1
}
This pattern allows skipping, jumping, or repeating specific elements.
Summary
The Swift while loop
is a flexible, powerful tool for repeating code based on dynamic conditions. It shines in scenarios where the number of iterations isn’t known ahead of time—such as input validation, countdowns, data polling, and condition-based simulations.
When you need guaranteed execution at least once, the repeat while loop Swift
syntax (equivalent to a swift do while loop
) has you covered. While loops also work well with control flow tools like break
, continue
, and optionals. Compared to for-in
loops, the while loop in Swift
gives you more freedom but requires you to manage conditions and index values manually.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.