Introduction to Swift | Control Statements | Repetition with while
A for statement includes a mechanism that changes on each iteration. There is also a simpler loop statement that only checks a condition to decide whether to repeat a process. This is the while statement.
There are two ways to write a while loop, depending on where the condition appears. The latter is also called a do while statement.
Basic form of while
while condition {
... repeated processing ...
}
Basic form of do while
do {
... repeated processing ...
} while condition
Write the condition after while. If the condition is true, the loop runs. When it becomes false, execution exits the loop.
Why are there two forms for such a simple operation? The difference is when the condition is checked. The first form, with while at the beginning, checks the condition before executing the block inside {}.
The second form, with while at the end, executes the block first and checks the condition afterward. As a result, the block runs at least once even if the condition is initially false.
Compare the following simple loops.
var n:Int = 0
while 10 > n++ {
"index:" + String(n)
}
var m:Int = 0
do {
"index:" + String(m)
} while 10 > m++
The first loop produces values in the form index:1 through index:10. The second loop produces index:0 through index:9. Because the variable is incremented with ++ in the condition, the values differ depending on whether the condition appears before or after the block.
As this example shows, the two forms behave slightly differently in subtle cases. As a general rule, use while by default and reserve do while for situations that require it.