Breaking out of a loop
Sometimes you want to break out of a loop early. You can do this using the break statement, which immediately stops the execution of the loop and continues on to the code after the loop.
For example, consider the following code:
var sum = 1
while true {
sum = sum + (sum + 1) if sum >= 1000 {
break
}
}
Here, the loop condition is true, so the loop would normally iterate forever. However, the break means the while loop will exit once the sum is greater than or equal to 1000. Neat!
You’ve seen how to write the same loop in different ways, demonstrating that in computer programming, there are often many ways to achieve the same result. You should choose the method that’s easiest to read and conveys your intent in the best way possible. This is an approach you’ll internalize with enough time and practice.