Swift - while 迴圈



在 Swift 程式語言中,while 迴圈語句會重複執行指定的語句,只要給定的條件為真。條件對於 while 迴圈至關重要,它可以防止迴圈變成無限迴圈。因此,始終檢查 while 迴圈中的條件。

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

語法

while 迴圈的語法如下:

while condition
{
   statement(s)
}

這裡statement(s) 可以是單個語句或語句塊。condition 可以是任何表示式。迴圈在條件為真時迭代。當條件變為假時,程式控制權將傳遞到迴圈後緊隨其後的行。

流程圖

以下流程圖將顯示 while 迴圈的工作原理:

While Loops

示例

以下 Swift 程式使用比較運算子 < 將變數 index 的值與 20 進行比較。當 index 的值小於 20 時,while 迴圈繼續執行緊隨其後的程式碼塊,一旦 index 的值變為等於 20,它就會退出。

import Foundation

var index = 10

// Here the loop continues executing until the index is less than 20  
while index < 20 {
   print( "Value of index is \(index)")
   index = index + 1
}

輸出

它將產生以下輸出:

執行上述程式碼時,將產生以下結果:

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

示例

使用 while 迴圈查詢總和的 Swift 程式。

import Foundation
var sum = 0
var num = 1

// Here the loop continues executing until num is less than equal to 9   
while num <= 9 {
   sum += num
   num += 1
}

print("Sum of numbers from 1 to 9 is: \(sum)")

輸出

它將產生以下輸出:

執行上述程式碼時,將產生以下結果:

Sum of numbers from 1 to 9 is: 45
廣告