This tutorial is part of the Swift series.
The while
loop in Swift is used to iterate over a block of code as long as a certain condition is true. The loop will continue running as long as the condition remains true.
The basic syntax of a while
loop is as follows:
while condition {
// statements to be executed
}
The condition is evaluated before the loop block is executed. If the condition is true, the loop block will be executed. Once the loop block finishes executing, the condition will be evaluated again. If the condition is still true, the loop block will be executed again. This process will continue until the condition becomes false.
Here’s an example to demonstrate how a while
loop works:
var item = 0
while item <= 3 {
print(item)
item += 1
}
In this example, we initialize a variable item
with a value of 0. The condition item <= 3
is checked at the beginning of each iteration. As long as the condition remains true, the loop block will be executed. Inside the loop block, we print the value of item
and then increment its value by 1. This process continues until item
becomes 4, at which point the condition becomes false and the loop terminates.
Tags: Swift, loops, while loop