Swift While 和 Repeat While 循环

17 Mar 2025 | 阅读 2 分钟

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

Swift 中有两种类型的循环

  1. While 循环
  2. Repeat While 循环

Swift While 循环

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

语法

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

  • 执行 while 循环内的语句。
  • 并且,再次评估 TestExpression。

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

While 循环的流程图

Swift while Statement

示例

输出

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 循环一直执行到条件评估为假,并且一旦获得假条件,它就会终止。