While loops are a fundamental control flow structure in Swift programming. They allow you to execute a block of code repeatedly as long as a specified condition remains true.
The basic syntax of a while loop in Swift is straightforward:
while condition {
// Code to be executed
}
The loop continues to execute as long as the condition evaluates to true. Once the condition becomes false, the loop terminates, and the program continues with the next statement after the loop.
Here's a simple example that demonstrates a while loop counting down from 5 to 1:
var countdown = 5
while countdown > 0 {
print("\(countdown)...")
countdown -= 1
}
print("Liftoff!")
This code will output:
5...
4...
3...
2...
1...
Liftoff!
Be cautious when using while loops to avoid creating infinite loops. An infinite loop occurs when the condition never becomes false. For example:
while true {
print("This will run forever!")
}
To prevent infinite loops, ensure that the condition will eventually become false or use a break statement to exit the loop when necessary.
While Swift for loops are typically used when you know the number of iterations in advance, while loops are more suitable when the number of iterations is unknown or depends on a condition that may change during execution.
Here's an example of using a while loop for input validation:
var userInput = ""
while userInput.isEmpty {
print("Please enter your name:")
userInput = readLine() ?? ""
}
print("Hello, \(userInput)!")
This loop continues to prompt the user for input until a non-empty string is provided.
While loops are a powerful tool in Swift for handling repetitive tasks with unknown iteration counts. By mastering while loops, you'll be able to write more flexible and efficient code for various programming scenarios.