
- Swift 教程
- Swift - 首頁
- Swift - 概述
- Swift - 環境
- Swift - 基本語法
- Swift - 變數
- Swift - 常量
- Swift - 字面量
- Swift - 註釋
- Swift 運算子
- Swift - 運算子
- Swift - 算術運算子
- Swift - 比較運算子
- Swift - 邏輯運算子
- Swift - 賦值運算子
- Swift - 位運算子
- Swift - 其他運算子
- Swift 高階運算子
- Swift - 運算子過載
- Swift - 算術溢位運算子
- Swift - 恆等運算子
- Swift - 範圍運算子
- Swift 資料型別
- Swift - 資料型別
- Swift - 整數
- Swift - 浮點數
- Swift - Double
- Swift - 布林值
- Swift - 字串
- Swift - 字元
- Swift - 類型別名
- Swift - 可選型別
- Swift - 元組
- Swift - 斷言和前提條件
- Swift 控制流
- Swift - 決策
- Swift - if 語句
- Swift - if...else if...else 語句
- Swift - if-else 語句
- Swift - 巢狀 if 語句
- Swift - switch 語句
- Swift - 迴圈
- Swift - for in 迴圈
- Swift - while 迴圈
- Swift - repeat...while 迴圈
- Swift - continue 語句
- Swift - break 語句
- Swift - fall through 語句
- Swift 集合
- Swift - 陣列
- Swift - 集合
- Swift - 字典
- Swift 函式
- Swift - 函式
- Swift - 巢狀函式
- Swift - 函式過載
- Swift - 遞迴
- Swift - 高階函式
- Swift 閉包
- Swift - 閉包
- Swift - 轉義和非轉義閉包
- Swift - 自動閉包
- Swift 面向物件程式設計
- Swift - 列舉
- Swift - 結構體
- Swift - 類
- Swift - 屬性
- Swift - 方法
- Swift - 下標
- Swift - 繼承
- Swift - 重寫
- Swift - 初始化
- Swift - 析構
- Swift 高階
- Swift - ARC 概述
- Swift - 可選鏈
- Swift - 錯誤處理
- Swift - 併發
- Swift - 型別轉換
- Swift - 巢狀型別
- Swift - 擴充套件
- Swift - 協議
- Swift - 泛型
- Swift - 訪問控制
- Swift - 函式與方法
- Swift - SwiftyJSON
- Swift - 單例類
- Swift 隨機數
- Swift 不透明和裝箱型別
- Swift 有用資源
- Swift - 線上編譯
- Swift - 快速指南
- Swift - 有用資源
- Swift - 討論
Swift - while 迴圈
在 Swift 程式語言中,while 迴圈語句會重複執行指定的語句,只要給定的條件為真。條件對於 while 迴圈至關重要,它可以防止迴圈變成無限迴圈。因此,始終檢查 while 迴圈中的條件。
while 迴圈的關鍵點在於迴圈可能永遠不會執行。當條件被測試且結果為假時,迴圈體將被跳過,並且將執行 while 迴圈之後的第一個語句。
語法
while 迴圈的語法如下:
while condition { statement(s) }
這裡statement(s) 可以是單個語句或語句塊。condition 可以是任何表示式。迴圈在條件為真時迭代。當條件變為假時,程式控制權將傳遞到迴圈後緊隨其後的行。
流程圖
以下流程圖將顯示 while 迴圈的工作原理:

示例
以下 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
廣告