Swift While Loop
A Swift while loop starts by evaluating a single condition. If the condition is true, a series of statements runs repeatedly until the condition becomes false.
Syntax
The syntax of a Swift while loop is as follows:
while condition
{
statement(s)
}
In the syntax, the statement(s) can be a single statement or a block of statements. condition can be an expression. If the condition is true, a series of statements runs repeatedly until the condition becomes false.
The number 0, the strings '0' and "", an empty list(), and undefined variables are all false , and everything else is true. Negating true uses ! the sign or not, returning false after negation.
Flow diagram:
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