Swift while and repeat while Loop

In this article, you will learn to create while and repeat...while loops in Swift programming.

In the previous article, we learned about for-in loop to run a set of tasks for a certain number of times. In this article, you will learn to use while and repeat..while as an alternative of for-in loop when the number of iteration is unknown.

A while loop executes a set of statements until a condition becomes false. These kinds of loops are best used when the number of iterations is not known before the first iteration begins. Swift provides two kinds of while loops:


1. Swift while Loop

This loop evaluates its condition at the start of each pass through the loop.

The syntax of while loop is:

while (TestExpression) {
    // statements
}

How while loop works?

The TestExpression is a boolean expression.

If the TestExpression is evaluated to true,

  • statements inside the while loop are executed.
  • and the TestExpressionis evaluated again.

This process goes on until the TestExpression is evaluated to false. If the TestExpression evaluates to false,while loop is terminated.


Flowchart of while Loop

Swift while loop flowchart


Example 1: While Loop

var currentLevel:Int = 0, finalLevel:Int = 5
let gameCompleted = true
while (currentLevel <= finalLevel) {
    //play game
    if gameCompleted {
        print("You have passed level \(currentLevel)")
        currentLevel += 1
    }
}
print("outside of while loop")

When you run the program, the output will be:

You have passed level 0
You have passed level 1
You have passed level 2
You have passed level 3
You have passed level 4
You have passed level 5
outside of while loop

In the above program, the variable currentLevel and finalLevel is initialized to 0 and constant gameCompleted is initialized to true.

In each iteration of while loop, it checks the condition currentLevel <= finalLevel. If the condition returns true, statements inside while loop is executed otherwise the loop terminates.

Execution steps
Iteration Condition (currentLevel <= finalLevel) Output
1 0 <= 5 (true) You have passed level 0
2 1 <= 5 (true) You have passed level 1
3 2 <= 5 (true) You have passed level 2
4 3 <= 5 (true) You have passed level 3
5 4 <= 5 (true) You have passed level 4
6 5 <= 5 (true) You have passed level 5
7 6 <= 5 (false) outside of while loop

2. Repeat while Loop

This loop evaluates its condition at the end of each pass through the loop.The repeat...while loop is similar to while loop with one key difference. The body of repeat...while loop is executed once before the test expression is checked.

The syntax of repeat..while loop is:

repeat {
    // statements
    ...
} while (testExpression)

How repeat...while loop works?

The body of repeat...while loop is executed once (before checking the test expression). Only then, testExpression is checked.

If testExpression is evaluated to true, statements inside the body of the loop are executed, and testExpression is evaluated again. This process goes on until testExpression is evaluated to false.

When testExpression is false, the repeat..while loop terminates.


Flowchart of repeat...while Loop

Swift repeat..while loop flowchart


Example 2: Repeat while Loop

var currentLevel:Int = 0, finalLevel:Int = 5
let gameCompleted = true
repeat {
    //play game
    if gameCompleted {
        print("You have passed level \(currentLevel)")
        currentLevel += 1
    }
} while (currentLevel <= finalLevel)
print("outside of repeat while loop")

When you run the program, the output will be:

You have passed level 0
You have passed level 1
You have passed level 2
You have passed level 3
You have passed level 4
You have passed level 5
outside of repeat while loop

In the above example, for the first time the statements inside the loop executes. And for next iteration, it checks the condition currentLevel <= finalLevel.

If the condition returns true, statements inside while loop is executed otherwise the loop terminates.

Execution steps
Iteration Condition (currentLevel <= finalLevel) Output
1 0 <= 5 (true) You have passed level 0
2 1 <= 5 (true) You have passed level 1
3 2 <= 5 (true) You have passed level 2
4 3 <= 5 (true) You have passed level 3
5 4 <= 5 (true) You have passed level 4
6 5 <= 5 (true) You have passed level 5
7 6 <= 5 (false) outside of repeat while loop

Although both while and repeat while loop have same execution steps, the condition currentLevel <= finalLevel on repeat while loop is executed only after executing the statements inside it.

But in while, the condition is checked at the beginning before executing the statements inside it.


3. Infinite while Loop

If the test expression never evaluates to false, the body of while and repeat..while loop is executed infinite number of times.

Example 3: Infinite while Loop

while (true) {
   print("Hello, World!")
}

 

repeat {
   print("Hello, World!")

} while (true)

When you run the program, the output will be:

Hello, World!
Hello, World!
.
.
.

When you run the program, both loop executes print("Hello, World!") statement for infinite number of times. So, you can see continuous output Hello, World! in the console.