Swift While和Repeat While循环
当迭代次数未知时,While和Repeat while循环被用作for-in循环的替代方案。While循环执行一组语句,直到条件为假为止。这种循环通常在你不知道迭代次数时使用。
在Swift中有两种类型的循环:
- While循环
- Repeat While循环
Swift While循环
Swift的While循环在每次执行时都会评估其条件。
语法
while (TestExpression) {
// statements
}
在这里,TestExpression是一个布尔表达式。如果它为真,则执行while循环中的语句。
- 在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条件,它就终止。