Easy Tutorial
❮ Swift Optionals Swift Generics ❯

Swift repeat...while Loop

Swift Loops

The Swift repeat...while loop is different from the for and while loops in that it does not evaluate the condition at the beginning of the loop body, but rather at the end of the loop execution.

Syntax

The syntax for a Swift repeat...while loop is as follows:

repeat {
   statement(s);
} while (condition);

Note that the condition expression is at the end of the loop, so the statement(s) within the loop will execute at least once before the condition is tested.

If the condition is true, the control flow will jump back to the repeat statement and the statement(s) within the loop will be executed again. This process will continue until the given condition becomes false.

The numbers 0, the string '0', "", an empty list(), and an undefined variable are all considered false, while everything else is considered true. The negation of true can be achieved using the ! operator or the not keyword, which will return false.

Flowchart:

Example

import Cocoa

var index = 15

repeat {
    print("The value of index is \(index)")
    index = index + 1
} while index < 20

The output of the above program is:

The value of index is 15
The value of index is 16
The value of index is 17
The value of index is 18
The value of index is 19

Swift Loops

❮ Swift Optionals Swift Generics ❯