图书连载13:for循环、while循环语句、repeat-while循环语句

3.3 循环语句和条件判断语句


3.3.1 for循环

Swift 的for循环语句,可以用来重复执行一系列语句,直到达成特定的条件。

Swift提供了两种for循环语句,一种是C语言风格的for循环:条件递增(for-condition-increment),这种方式在Swift 3.0中被遗弃,所以这里只讲解Swift推荐使用的for-in循环。

1     for index in 0 ..< 3
2     {
3         print("index is \(index)")
4     }

在for-in语句中,..<符号表示数值范围在0至3之间,但是并不包含数字3,所以打印刷出的结果如下:

index is 0
index is 1
index is 2

如果需要在循环中包含数字3,可以使用...符号:

1     for index in 0 ... 3
2     {
3         print("index is \(index)")
4     }

以上代码在控制台输出的结果为:

index is 0
index is 1
index is 2
index is 3

for-in循环语句用途广泛,我们曾经在3.2.4节中,对字符串中的字符进行遍历。您还可以使用该语句,对数组和字典进行遍历。

1     let students =["Jerry","Thomas","John"]
2     for student in students {
3        print("Student name:\(student)")
4     }

以上代码在控制台输出的结果为:

Student name:Jerry
Student name:Thomas
Student name:John

通过for-in循环语句,可以遍历一个字典来的键值对(key-valuepairs)。在遍历字典时,字典的每项元素会以(key,value)元组的形式返回。

1     let scores = ["Jerry":78,"Thomas":88,"John":92]
2     for (student,score) in scores
3     {
4          print(student + "' score is\(score)")
5     }

以上代码在控制台输出的结果为:

John' score is 92
Jerry' score is 78
Thomas' score is 88     

因为字典的内容在内部是无序的,所以遍历元素时不能保证与其插入的顺序一致,字典元素的遍历顺序和插入顺序可能不同。



3.3.2 while循环语句

Swift的while循环语句,和Object-C的while语句非常相似,主要用于重复执行某个代码块。while语句的样式如下所示:

while condition {
statements
}

其中condition为执行循环语句的条件,其值如果为true,则执行大括号里面的代码块。如果为false,while语句执行完毕。

1     var index = 0
2     while index < 3
3     {
4         index += 1
5         print("Try connect serveragain.")
6     }
 
以上while语句的执行结果为:
Try connect serveragain.
Try connect serveragain.
Try connect serveragain.




3.3.3 repeat-while循环语句

Swift 1.0中的do-while语句,在Swift 2.2中已经被repeat-while语句所替换,但是使用方法和传统的do-while语句是一致的,现在将上面例子中的while语句修改一下:

1     var index = 0
2     repeat
3     {
4         index += 1
5         print("Try connect serveragain.")
6     }
7     while index < 3

以上repeat-while语句的执行结果为:

Try connect serveragain.
Try connect serveragain.
Try connect serveragain.

由于repeat-while语句是先执行代码块,再进行条件的判断,所以代码段总会被执行至少一次。将上面代码中的条件判断语句修改为:

1     var index = 0
2     repeat
3     {
4         index += 1
5         print("Try connect serveragain.")
6     }
7     while index < 0

以上repeat-while语句的执行结果为:

Try connect serveragain.




一个人写书,难免会有不足和纰漏,欢迎大家通过这个邮箱:coolketang@163.com

将你的意见和建议告诉我们,感谢!

关注我的微信公众号“酷课堂”,获取更多学习资源,欢迎留言交流。

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...