详解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
您可能感兴趣的文章:
相关文章推荐
- Apple Swift学习教程
- Swift中实现点击、双击、捏、旋转、拖动、划动、长按手势的类和方法介绍
- Swift中定义二维数组的方法及遍历方法示例
- 简单分析Swift语言的一些基本特征
- Swift与C语言指针结合使用实例
- Swift心得笔记之控制流
- 用Swift构建一个简单的iOS邮件应用的方法
- 苹果公司推出的新编程语言Swift简介和入门教程
- Swift中的指针操作和使用详细介绍
- Swift中使用正则表达式的一些方法
- Swift心得笔记之运算符
- Swift中使用可选类型完美解决占位问题
- Swift学习笔记之构造器重载
- Swift中的Access Control权限控制介绍
- Swift类型创建之自定义一个类型详解
- Swift教程之控制流详解
- Swift中初始化方法的顺序介绍
- Swift里的值类型与引用类型区别和使用
- Swift调用Objective-C编写的API实例