Swift while迴圈

2019-10-16 23:14:10

只要給定條件為真,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