Swift While循环

Swift While循环

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

语法

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

while condition {
   statement(s)
}

在这里, 语句 可以是一个单独的语句或一系列语句。 条件 可以是任何表达式。当条件为真时,循环迭代。当条件变为假时,程序控制流传递到紧接在循环后的那一行。

数字0,字符串’0’和””,空列表()和undef都在布尔上下文中是 ,而其他所有值都是 。通过 !not 对真值进行取反会返回一个特殊的假值。

流程图

Swift While循环

while循环的关键点是循环可能根本就不会运行。当条件被测试并且结果为假时,循环体将被跳过,while循环后的第一条语句将被执行。

示例

var index = 10

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

在这里,我们使用比较运算符<来比较变量 index 的值与20。当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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程