In Swift, a “while” loop is used to repeatedly execute a block of code until a specific condition is no longer true. The basic syntax for a `while` loop is as follows:
while condition { // code to be executed }
The loop will continue executing the code block as long as the “condition” is true. Once the “condition” becomes false, the loop will exit and the program will move on to the next line of code after the loop.
var count = 0 while count < 5 { print(count) count += 1 } /* Output 0 1 2 3 4 */
Quick notes
- In this code, the “while” loop will continue executing as long as “count” is less than 5.
- Inside the loop, the current value of “count” is printed to the console and then “count” is incremented.
- Once “count” becomes equal to 5, the “condition” is no longer true and the loop exits.
- “while” loops can be useful when you want to execute a block of code a specific number of times or until a specific condition is met.
- When writing a “while” loop, it’s important to make sure that the “condition” will eventually become false, or else the loop will continue executing indefinitely, which can cause the program to become unresponsive.
In summary, a “while” loop in Swift is used to repeatedly execute a block of code as long as a specific condition is true.
Countdown example using a “while” loop
Here’s another way to use a “while” loop to generate a countdown:
var count = 10 while count > 0 { print(count) count -= 1 } print("FIRE!") /* Output 10 9 8 7 6 5 4 3 2 1 FIRE! */