In Swift, while
and repeat-while
loops provide an alternative to for
loops when you need to repeat a block of code until a specific condition is met. Unlike for
loops, which are generally used when the number of iterations is known ahead of time, while
and repeat-while
loops are used when the number of iterations is unknown, but you want the loop to run based on a condition.
In this article, we’ll explore how while
and repeat-while
loops work in Swift, the differences between them, and when you should use each loop. We’ll also cover common use cases, examples, and best practices for using these loops effectively.
Swift while
Loop
A while
loop repeats a block of code as long as a condition remains true. The condition is evaluated before the loop executes, so if the condition is false at the start, the loop does not execute at all.
The syntax for a while
loop is:
while condition {
// Code to execute
}
The loop continues running as long as the condition
evaluates to true
.
Example 1: Basic while
Loop
var count = 1
while count <= 5 {
print("Count is \(count)")
count += 1
}
Output:
Count is 1
Count is 2
Count is 3
Count is 4
Count is 5
In this example, the while
loop runs as long as count
is less than or equal to 5
. After each iteration, the count
variable is incremented, eventually causing the loop to exit when count
reaches 6
.
Using while
Loops for Unknown Iterations
The while
loop is especially useful when you don’t know ahead of time how many iterations are needed, but you want the loop to continue until a certain condition is met.
Example 2: while
Loop with User Input
var input: String?
while input != "exit" {
print("Type 'exit' to stop")
input = readLine()
}
In this example, the while
loop repeatedly prompts the user for input and stops only when the user types "exit"
. The number of iterations is unknown, and the loop continues until the condition input != "exit"
is false.
Swift repeat-while
Loop
The repeat-while
loop is similar to the while
loop, but with one key difference: the condition is evaluated after the loop body has executed. This means the loop always runs at least once, even if the condition is false on the first check.
The syntax for a repeat-while
loop is:
repeat {
// Code to execute
} while condition
Example 3: Basic repeat-while
Loop
var count = 1
repeat {
print("Count is \(count)")
count += 1
} while count <= 5
Output:
Count is 1
Count is 2
Count is 3
Count is 4
Count is 5
In this example, the repeat-while
loop behaves similarly to the while
loop, but the condition is checked after each iteration. This guarantees that the code inside the loop runs at least once, regardless of the initial value of count
.
Key Differences Between while
and repeat-while
The primary difference between while
and repeat-while
loops is when the condition is checked:
- In a
while
loop, the condition is checked before the loop body executes. If the condition is false from the start, the loop body does not execute. - In a
repeat-while
loop, the condition is checked after the loop body executes. The loop body is guaranteed to run at least once, even if the condition is initially false.
Example 4: Comparing while
and repeat-while
var a = 10
var b = 10
// while loop
while a < 5 {
print("This won't print because a is already 10.")
}
// repeat-while loop
repeat {
print("This will print once, even though b is 10.")
} while b < 5
Output:
This will print once, even though b is 10.
In this example, the while
loop does not execute because the condition is false from the start. However, the repeat-while
loop executes once, even though the condition is false, because the condition is checked after the first iteration.
Practical Uses of while
and repeat-while
Loops
Example 5: Using a while
Loop to Simulate a Countdown Timer
var seconds = 5
while seconds > 0 {
print("\(seconds) seconds left...")
seconds -= 1
}
print("Time's up!")
Output:
5 seconds left...
4 seconds left...
3 seconds left...
2 seconds left...
1 second left...
Time's up!
In this example, the while
loop simulates a countdown timer. The loop continues running until seconds
reaches zero.
Example 6: Using a repeat-while
Loop to Ensure Valid Input
var password: String?
repeat {
print("Enter your password:")
password = readLine()
} while password == nil || password!.isEmpty
print("Password accepted.")
In this example, the repeat-while
loop ensures that the user is prompted to enter a password at least once, and it continues to prompt the user until a valid password (non-empty input) is provided.
Breaking Out of Loops Early
You can use the break
statement to exit a while
or repeat-while
loop early if a certain condition is met.
Example 7: Breaking Out of a while
Loop
var number = 1
while number <= 10 {
if number == 5 {
print("Exiting the loop at number \(number)")
break
}
number += 1
}
Output:
Exiting the loop at number 5
In this example, the while
loop exits early when number
reaches 5
due to the break
statement.
Skipping Iterations
You can use the continue
statement to skip the current iteration of a while
or repeat-while
loop and move on to the next iteration.
Example 8: Skipping Iterations in a while
Loop
var i = 0
while i < 10 {
i += 1
if i % 2 == 0 {
continue // Skip even numbers
}
print(i)
}
Output:
1
3
5
7
9
In this example, the continue
statement skips the even numbers, allowing only the odd numbers to be printed.
Infinite Loops
A while loop or repeat-while loop can become an infinite loop if the condition never evaluates to false
. This can be intentional in some cases (e.g., waiting for an external event), but you should always ensure that there is a way to exit the loop eventually.
Example 9: Intentional Infinite Loop
while true {
print("This loop will run forever unless stopped manually.")
break // Prevent infinite loop
}
In this example, the while true
loop is intentionally infinite, but the break
statement is used to exit the loop and prevent it from running forever.
Best Practices for Using while
and repeat-while
Loops
- Use
while
when the number of iterations is unknown: If you need a loop that runs based on a condition rather than a fixed number of iterations, use awhile
loop. - Use
repeat-while
when you need the loop to run at least once: If you want to ensure that the loop body executes at least once before checking the condition, use arepeat-while
loop. - Avoid infinite loops unless necessary: Be careful when using loops with conditions that might never become
false
. Always ensure there’s a clear way for the loop to exit to avoid infinite loops. - Use
break
andcontinue
wisely: Usebreak
to exit a loop early when necessary andcontinue
to skip specific iterations.
Conclusion
Swift’s while
and repeat-while
loops provide flexibility when you need to repeat a block of code based on a condition. While loops are ideal when the number of iterations is unknown, and the condition is checked before the loop runs, whereas repeat-while loops are perfect for situations where you need the loop to execute at least once before checking the condition.
In this article, we covered:
- The syntax and usage of
while
andrepeat-while
loops. - Key differences between
while
andrepeat-while
. - Practical use cases for each loop type.
- Breaking out of loops early with
break
and skipping iterations withcontinue
.
In the next article, we’ll explore Swift Nested Loops—how to use loops within loops
to process multidimensional data and perform complex iterations.
Happy coding!