Swift while迴圈

只要給定條件為真,Swift 4編程語言中的while迴圈語句就會重複執行目標語句。

語法

Swift 4編程語言中while迴圈的語法是 -

while condition {
   statement(s)
}

這裏的語句(statement)可以是單個語句或多個語句塊。 條件(condition)可以是任何運算式。 當條件為真時,迴圈迭代。 當條件變為假時,程式控制傳遞到緊接迴圈之後的行。

數字0,字串'0'"",空列表()undef在布爾上下文中都是false,所有其他值都為true。 否定true值使用運算符:!not則返回false值。

流程圖

while迴圈的關鍵點是迴圈可能永遠不會運行。 當測試條件並且結果為false時,將跳過循環體並且將執行while迴圈之後的第一個語句。

示例

var index = 10

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

這裏使用比較運算符<來將變數index20的值比較。當index的值小於20時,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字串