Swift 迴圈 (Loops)

Swift 提供了多種方式來重複執行程式碼塊。

For-In 迴圈

for-in 是 Swift 最常用的迴圈,用於遍歷序列 (Sequence),如陣列、數字區間、或字串中的字元。

遍歷區間

for index in 1...5 {
    print("\(index) * 5 = \(index * 5)")
}

如果你不需要區間內的數值,可以用底線 _ 替代變數名:

let base = 3
let power = 10
var answer = 1
for _ in 1...power {
    answer *= base
}

遍歷陣列

let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names {
    print("Hello, \(name)!")
}

遍歷字典

let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
for (animalName, legCount) in numberOfLegs {
    print("\(animalName)s have \(legCount) legs")
}

While 迴圈

while 迴圈會在條件為 true 時持續執行。適用於不知道需要執行幾次的狀況。

var count = 5
while count > 0 {
    print(count)
    count -= 1
}
print("Blastoff!")

Repeat-While 迴圈

這相當於其他語言中的 do-while 迴圈。它保證至少執行一次程式碼塊,然後才檢查條件。

var i = 0
repeat {
    print("這個數字是 \(i)")
    i += 1
} while i < 3

控制轉移語句

用來改變迴圈的執行順序。

  • continue:跳過本次迴圈的剩餘部分,直接開始下一次迴圈。
  • break:完全終止迴圈,跳出大括號。
for i in 1...10 {
    if i % 2 == 0 {
        continue // 跳過偶數
    }
    if i > 7 {
        break // 大於 7 就結束
    }
    print(i)
}
// 輸出:1, 3, 5, 7