Swift do...while循环

与在循环顶部测试循环条件的forwhile循环不同,repeat ... while循环检查循环底部的条件。

repeat ... while循环类似于while循环,但是repeat ... while循环保证至少执行一次。

语法

Swift 4中的repeat ... while循环的语法是 -

repeat {
   statement(s);
} 
while( condition );

应该注意的是,条件表达式出现在循环的末尾,因此循环中的语句在测试条件之前执行一次。 如果条件为真,则控制流跳回到重复,并且循环中的语句再次执行。 重复此过程直到给定条件变为假。
数字0,字符串'0'"",空列表()undef在布尔上下文中都是false,所有其他值都为true。 否定true值使用运算符!not返回false值。

流程图

示例代码

var index = 10

repeat {
   print( "Value of index is \(index)")
   index = index + 1
}
while index < 20

执行上述代码时,会产生以下结果 -

Value of index is 10
Value of index is 11
Value of index is 12
Value of index is 13
Value of index is 14
Value of index is 15
Value of index is 16
Value of index is 17
Value of index is 18
Value of index is 19

上一篇: Swift循环语句 下一篇: Swift字符串