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

图书连载13:for循环、while循环语句、repeat-while循环语句,第1张

概述                                               3.3  循环语句和条件判断语句 3.3.1  for循环 Swift 的for循环语句,可以用来重复执行一系列语句,直到达成特定的条件。 Swift提供了两种for循环语句,一种是C语言风格的for循环:条件递增(for-condition-increment),这种方式在Swift 3.0中被遗弃,所

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 ..< 32     {3         print("index is \(index)")4     }

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

index is 0index is 1index is 2

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

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

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

index is 0index is 1index is 2index 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:JerryStudent name:ThomasStudent name:John

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

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

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

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

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



3.3.2 while循环语句

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

while condition {statements}

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

1     var index = 02     while index < 33     {4         index += 15         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 = 02     repeat3     {4         index += 15         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 = 02     repeat3     {4         index += 15         print("Try connect serveragain.")6     }7     while index < 0

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

Try connect serveragain.




一个人写书,难免会有不足和纰漏,欢迎大家通过这个邮箱:[email protected]

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

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

总结

以上是内存溢出为你收集整理的图书连载13:for循环、while循环语句、repeat-while循环语句全部内容,希望文章能够帮你解决图书连载13:for循环、while循环语句、repeat-while循环语句所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1067719.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-26
下一篇 2022-05-26

发表评论

登录后才能评论

评论列表(0条)

保存