当迭代次数未知时, 将While和Repeat while循环用作for-in循环的替代方法。 while循环执行一组语句, 直到出现错误条件为止。当你不知道迭代次数时, 通常使用此循环。
Swift中有两种类型的循环:
- while循环
- 重复While循环
句法:
while (TestExpression) {// statements}
【Swift While和Repeat While循环语句用法】在这里, TestExpression是一个布尔表达式。如果是真的
- 在while循环内的语句被执行。
- 并且, 再次对TestExpression求值。
While循环流程图
文章图片
例:
var currentLevel:Int = 0, finalLevel:Int = 6let gameCompleted = truewhile (currentLevel <
= finalLevel) {//play gameif gameCompleted {print("You have successfully completed level \(currentLevel)")currentLevel += 1}}//outside of while loopprint("Terminated! You are out of the game ")
输出
You have successfully completed level 0You have successfully completed level 1You have successfully completed level 2You have successfully completed level 3You have successfully completed level 4You have successfully completed level 5You have successfully completed level 6Terminated! You are out of the game
在上面的程序中, 执行while循环, 直到条件被评估为false为止, 并在获得false条件后立即终止。
推荐阅读
- Swift repeat-while循环语句用法示例
- Swift for-in循环语句介绍和用法示例
- Swift 4循环语句基本介绍
- Swift break语句介绍用法示例
- Windows的20款最佳免费2D动画软件下载推荐(哪个最好())
- 如何修复Windows 10 Chrome插件不起作用(解决办法教程)
- 如何修复Windows 10 Microsoft Store无法运行(解决办法介绍)
- 如何修复Windows 10中的Excel stdole32.tlb错误(解决办法)
- 30款最佳初学者CAD软件下载推荐合集(哪个最好用())