In this Swift tutorial, you will learn about the Swift while loop with some examples.
In the programming world, a loop is used to repeat a block of code multiple times. For example, you can print the “Hello World” text 100 times or even 1000 times.
Below is the given syntax for Swift while
loop:
while (condition){ // code block of body }
In the above syntax, the while loop checks the condition inside the parenthesis ()
. If the condition
becomes true
, the code inside the loop will be executed.
The process of running the code inside the loop will continue until the condition
become false
. When the condition
becomes false
, the code inside the loop will not run anymore and thus the loop will stop.
Below is given the given flowchart diagram of the while loop:
The above diagram shows how a while loop works.
Now let’s see the example of while loops in Swift programming.
// Declaring the variables
var i = 0, j = 7
// while loop from i = 0 to 7
while (i <= j) {
print(i)
i = i + 1
}
Output:
0 1 2 3 4 5 6 7
In the above example, we are evaluating if i
is less than or equal to j
in the parenthesis of the while loop (i <= j)
. Inside the while loop, we are gradually increasing i
value by 1 each time the code block of the while loop run.
When the value of i
will be greater than the j
value, the condition will become false
as our condition only evaluates if i
is less than or equal to j
. So the loop will close.
You can also iterate over a Swift array using the while loop as you can see in the example below:
var colors = ["Green", "Red", "Yellow", "Black"]
var i = 0
while i < colors.count {
let color = colors[i] //access ith element of colors array
print(color)
i += 1
}
Output:
Green
Red
Yellow
Black
As you can see in the above code, we have an array colors
that contains some names of colors as the array elements. Using the while loop, we are able to iterate over the array and print each name of the color.
Here we have first counted the number of array elements and then checked running the while loop with a condition until i
value becomes greater than the value of array length.