Swift While和Repeat While循环

Swift While和Repeat While循环

当迭代次数未知时,While和Repeat while循环被用作for-in循环的替代方案。While循环执行一组语句,直到条件为假为止。这种循环通常在你不知道迭代次数时使用。

在Swift中有两种类型的循环:

  1. While循环
  2. Repeat While循环

Swift While循环

Swift的While循环在每次执行时都会评估其条件。

语法

while (TestExpression) {
    // statements
}

在这里,TestExpression是一个布尔表达式。如果它为真,则执行while循环中的语句。

  • 在while循环中,语句将被执行。
  • 然后,TestExpression将再次进行评估。

这个过程会一直进行,直到TestExpression为假为止。当TestExpression得到假条件时,while循环终止。

While循环的流程图

Swift While和Repeat While循环

示例

var currentLevel:Int = 0, finalLevel:Int = 6
let gameCompleted = true
while (currentLevel <= finalLevel) {
    //play game
    if gameCompleted {
        print("You have successfully completed level \(currentLevel)")
        currentLevel += 1
    }
}
//outside of while loop
print("Terminated! You are out of the game ")

输出:

You have successfully completed level 0
You have successfully completed level 1
You have successfully completed level 2
You have successfully completed level 3
You have successfully completed level 4
You have successfully completed level 5
You have successfully completed level 6
Terminated! You are out of the game 

在上面的程序中,while循环执行直到条件被评估为false,并且一旦获得false条件,它就终止。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程