Swift repeat…while Loop


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.

Syntax of the repeat...while loop

Below is the given syntax for the repeat...while loop:

repeat {
  // body statement of the loop
} while (condition)

In the above code syntax:

  • The body of the above syntax will be executed first, after that the condition is going to be evaluated.
  • If the condition is true, the body will execute again and then again the condition will be checked. This process continues until the condition evaluates false.
  • After the condition is false, the loop will stop execution.

Flowchart of the repeat…while loop

Below is given the flowchart diagram of a repeat while loop:

Swift repeat-while loop
Flowchart of Swift repeat-while loop

You can look at the above diagram to notice carefully to understand the working of a repeat...while loop.

Examples

Now let’s see some examples of Swift programs for a repeat...while loop:

Example 1:

// 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.

Example 2: Using repeat...while loop to loop through an array

Below 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.