I have already discussed the while loop
in my previous tutorial. Now in this tutorial, you will learn about the Swift repeat…while loop.
The Swift repeat...while
loop is the same as the while
loop with an important difference that makes it separate.
In repeat…while loop, the code block in the loop body is executed first before checking the condition. After the execution of the code block in the body statement, the condition will be checked. After that, it will execute the statements repeatedly till the defined condition is TRUE.
repeat...while
loopBelow is the given syntax for the repeat...while
loop:
repeat {
// body statement of the loop
} while (condition)
In the above code syntax:
Below is given the flowchart diagram of a repeat while loop:
You can look at the above diagram to notice carefully to understand the working of a repeat...while
loop.
Now let’s see some examples of Swift programs for a repeat...while
loop:
// Initializing the variable
var i = 1
// repeat...while loop to print from 1 to 7
repeat {
print(i)
i = i + 1
} while (i <= 7)
Output:
1
2
3
4
5
6
7
In the above example, we have initialized a variable i. At the very first our loop simply print the value of this variable which is 1. After that, we are increasing the value each time the loop run until it reaches 7.
In our condition, we are evaluating if the value of i is equal to or less than 7. When the value of i
exceeds 7, the loop stops.
repeat...while
loop to loop through an arrayBelow is another example where we are looping over an array using the Swift repeat...while
loop:
var colors = ["Green", "Red", "Yellow", "Black"]
var i = 0
repeat {
let color = colors[i] //access ith element of colors array
print(color)
i += 1
} while (i < colors.count)
Output:
Green
Red
Yellow
Black
In the above code, we are increasing the i
value as long as it is not reaching the length of the array. Thus we are printing each array item by the index number in the loop. Here the i
value is the index number.