您的位置:首页 > 移动开发 > Swift

详解Swift语言的while循环结构

2015-11-03 17:11 579 查看

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

语法
Swift 编程语言的 while 循环的语法是:

复制代码 代码如下:
while condition
{
   statement(s)
}

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

数字0,字符串“0”和“”,空列表 list(),和 undef 全是假的在布尔上下文中,除此外所有其他值都为 true。否定句一个真值 !或者 not 则返回一个特殊的假值。

流程图

while循环在这里,关键的一点:循环可能永远不会运行。当在测试条件和结果是假时,循环体将跳过while循环,之后的第一个语句将被执行。

示例

复制代码 代码如下:
import Cocoa
 
var index = 10

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


在这里,我们使用的是比较操作符 < 来比较 20 变量索引值。因此,尽管索引的值小于 20,while 循环继续执行的代码块的下一代码,并叠加指数的值到 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

do...while循环
不像 for 和 while 循环,在循环顶部测试循环条件,do...while 循环检查其状态在循环的底部。

do... while循环类似于while循环, 不同之处在于 do...while 循环保证执行至少一次。

语法
在 Swift 编程语言中的 do...while 语法如下:

复制代码 代码如下:
do
{
   statement(s);
}while( condition );

应当指出的是,条件表达式出现在循环的底部,所以在测试条件之前循环语句执行一次。如果条件为真,控制流跳回起来继续执行,循环语句再次执行。重复这个过程,直到给定的条件为假。

数字 0,字符串 “0” 和 “” ,空列表 list(),和 undef 全是假的在布尔上下文中,除此外所有其他值都为 true。否定句一个真值 !或者 not 则返回一个特殊的假值。

流程图

实例

复制代码 代码如下:
import Cocoa
 
var index = 10

do{
   println( "Value of index is \(index)")
   index = index + 1
}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