與在迴圈頂部測試迴圈條件的for
和while
迴圈不同,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