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字串