
The while loops
The while loops execute the body of the loop (list of the statements in the body part) until the condition is evaluated to false.
There are two types of while loops. There is the classical while loop, which checks the condition, and, if it holds, then the code in the body is executed. Then the check is performed again and everything is repeated until the condition is evaluated to false. The other variant is the repeat...while loop, which first executes the body, and then does the check. The second type is executed at least once, compared to the first one, which could be completely skipped:
var i = 1
let max = 10
var sum = 0
while i <= max {
sum += i
i += 1
}
print("Sum: \(sum)")
The code sums all numbers from 1 to 10. The condition will be broken once i reaches 11.
We can use repeat...while to do the same:
var i = 1
let max = 10
var sum = 0
repeat {
sum += i
i += 1
} while i <= max
print("Sum: \(sum)")
We can use while to implement the repeat...while loops and the reverse, but with slight modifications. The best rule for picking the right type of loop is to know whether the sequence should be executed at least once. Executing once means that it's much easier to implement it using repeat...while; otherwise, the classical while loop is the best choice.
There are some special conditions which we should handle, but to do so, let's see what they are.
We can use the special words—continue and break—to trigger special behavior while we are in a loop. The continue statement is used when you want to stop the current iteration of the loop and start over. When using this, be careful that you change the value in the condition; otherwise, the loop could be an infinite one, which means that your program won't end.
The break statement is used once we want to stop the entire loop. Be careful when you have nested loops. The break statement stops the current iteration immediately, and then jumps to the very first line after the end of the innermost loop, which contains the break statement. If you want to break two or more nested loops, then you have to find an appropriate way to do so. To be explicit when breaking nested loops, you may use labeled statements. It is a convenient way to give a name of a loop and then to change the flow when using break. It's good to know that break may be used as part of a switch statement. This will be discussed in the next part.
There are a few other special words, such as return , throw, and fallthrough which change the default order of execution of the code. We will get familiar with these later.