Easy Tutorial
❮ Swift Functions Swift For Loop ❯

Swift While Loop

Swift Loops

Swift while loops start by evaluating a single condition. If the condition is true, a series of statements will be executed repeatedly until the condition becomes false.

Syntax

The syntax for a Swift while loop is as follows:

while condition
{
   statement(s)
}

The statement(s) can be a single statement or a block of statements. condition can be an expression. If the condition is true, the series of statements will be executed repeatedly until the condition becomes false.

The numbers 0, the string '0', "", empty list(), and undefined variables are false, while everything else is true. The negation of true uses the ! or not operator, which returns false when negated.

Flowchart:

Example

import Cocoa

var index = 10

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

The output of the above program is:

index 的值为 10
index 的值为 11
index 的值为 12
index 的值为 13
index 的值为 14
index 的值为 15
index 的值为 16
index 的值为 17
index 的值为 18
index 的值为 19

Swift Loops

❮ Swift Functions Swift For Loop ❯