Swift while Loop
In Swift, you can execute code repeatedly (loop) using a for-in loop, a while loop, or a repeat-while loop.
In this article, we'll look at the while statement and the repeat-while statement in Swift.
The while Statement in Swift
The while statement in Swift executes a block of code repeatedly as long as a given condition is true.
It's useful when the number of iterations is not known in advance.
while [condition] {
// Code block executed in the loop
}
If the condition is false from the start, the code block will not be executed even once.
When the condition becomes false during the loop, the code block is skipped and the loop exits.
If the condition never becomes false, it will result in an infinite loop, and the code block will keep running forever, so be careful.
Let's try using a while loop in Swift.
We'll initialize a variable i to 1 and repeat the loop while i is less than 10.
Inside the loop, we print i and increment it by 2 each time.
After the loop finishes, we also print the final value of i.
var i = 1
while i < 10 {
print("i = \(i)")
i += 2
}
print("final i = \(i)")
The output will look like this. When i becomes 11, the condition is false and the loop exits.
i = 1
i = 3
i = 5
i = 7
i = 9
final i = 11
The repeat-while Statement in Swift
The repeat-while statement in Swift is similar to the while statement, but it checks the condition after executing the code block.
repeat {
// Code block executed in the loop
} while [condition]
This means that the code block will always execute at least once, even if the condition is false initially.
As with while loops, if the condition never becomes false, you'll end up with an infinite loop.
Let's try using a repeat-while loop in Swift.
We'll write the same logic as before, but this time with a repeat-while statement.
var i = 1
repeat {
print("i = \(i)")
i += 2
} while i < 10
print("final i = \(i)")
The output is as follows. When i becomes 11, the condition is false and the repeat-while loop exits.
i = 1
i = 3
i = 5
i = 7
i = 9
final i = 11
If you change the condition in both examples from i < 10 to i < 1, you'll see the difference: with while, the code block won't run at all, but with repeat-while, it runs once before checking the condition.
That wraps up our explanation of the while and repeat-while statements in Swift.