Swift repeat...while Loop

Swift 循环Swift Loops

Unlike the for and while loops, which test the condition before the loop body begins executing, the Swift repeat...while loop tests the condition at the end of the loop execution.

Syntax

The syntax format of the Swift repeat...while loop is as follows:

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

Note that the conditional expression appears at the end of the loop, so the statement(s) in the loop will be executed at least once before the condition is tested.

If the condition is true, the control flow jumps back to the repeat above and re-executes the statement(s) in the loop. This process repeats continuously until the given condition becomes false.

The number 0, the string '0' and "", an empty list(), and undefined variables are allfalse, while all others aretrue. To negate true, use!sign ornot, and returns false after negation.

Flowchart:

Example

import Cocoa

var index = 15

repeat{
    print( "index 的值为 \(index)")
    index = index + 1
}while index < 20

The output of the above program execution is:

index 的值为 15
index 的值为 16
index 的值为 17
index 的值为 18
index 的值为 19

Swift 循环Swift Loops

Other Extensions