Swift while循环

只要给定条件为真,Swift 4编程语言中的while循环语句就会重复执行目标语句。

语法

Swift 4编程语言中while循环的语法是 -

while condition {
   statement(s)
}

这里的语句(statement)可以是单个语句或多个语句块。 条件(condition)可以是任何表达式。 当条件为真时,循环迭代。 当条件变为假时,程序控制传递到紧接循环之后的行。

数字0,字符串'0'"",空列表()undef在布尔上下文中都是false,所有其他值都为true。 否定true值使用运算符:!not则返回false值。

流程图

while循环的关键点是循环可能永远不会运行。 当测试条件并且结果为false时,将跳过循环体并且将执行while循环之后的第一个语句。

示例

var index = 10

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

这里使用比较运算符<来将变量index20的值比较。当index的值小于20时,while循环继续执行它旁边的代码块,并且当index的值等于20时,它跳出来循环体。上面的代码产生以下结果 -

Value of index is 10
Value of index is 11
Value of index is 12
Value of index is 13
Value of index is 14
Value of index is 15
Value of index is 16
Value of index is 17
Value of index is 18
Value of index is 19

上一篇: Swift循环语句 下一篇: Swift字符串