📜  Swift While循环

📅  最后修改于: 2021-01-11 07:41:05             🧑  作者: Mango

Swift While和Repeat While循环

当迭代次数未知时,将While和Repeat while循环用作for-in循环的替代方法。 while循环执行一组语句,直到出现错误条件为止。当您不知道迭代次数时,通常使用此循环。

Swift中有两种类型的循环:

迅捷的While循环

Swift while循环在每次传递开始时评估其条件。

句法:

while (TestExpression) {
    // statements
}

在这里,TestExpression是一个布尔表达式。如果是真的

  • 在while循环内的语句被执行。
  • 并且,再次对TestExpression求值。

这个过程一直持续到TestExpression的值为假。当TestExpression获得错误条件时,while循环终止。

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条件后立即终止。