Skip to main content

for-loop

在 Swift 裡 for loop 有幾種常見寫法,我幫你整理成清單 👇

🔹 1. 基本範圍迴圈

for i in 1...5 {   // 包含 1 到 5
print(i)
}
// 印出 1 2 3 4 5

for i in 1..<5 { // 包含 1 到 4,不包含 5
print(i)
}
// 印出 1 2 3 4

🔹 2. 迭代陣列

let fruits = ["apple", "banana", "cherry"]

for fruit in fruits {
print(fruit)
}
// 印出 apple banana cherry

🔹 3. 搭配 enumerated()(拿到索引)

let fruits = ["apple", "banana", "cherry"]

for (index, fruit) in fruits.enumerated() {
print("\(index): \(fruit)")
}
// 0: apple
// 1: banana
// 2: cherry

🔹 4. 搭配 stride(自訂步長)

for i in stride(from: 0, to: 10, by: 2) {
print(i)
}
// 印出 0 2 4 6 8

🔹 5. 忽略變數(只執行多次)

for _ in 1...3 {
print("Hello")
}
// 印出 Hello 三次

🔹 6. 巢狀迴圈

for i in 1...3 {
for j in 1...2 {
print("i=\(i), j=\(j)")
}
}

要不要我幫你整理一個 Swift 的 for loop 對比 JavaScript 的寫法表格?這樣如果你有 JS 背景會更快上手。

在 Swift 裡的 「object」 如果你指的是 Dictionary(物件結構 key → value),那就可以直接用 for-in 來迭代。

🔹 迭代 Dictionary

let user = [
"name": "Thomas",
"city": "Taipei",
"job": "Developer"
]

for (key, value) in user {
print("\(key): \(value)")
}

可能輸出(順序不固定):

city: Taipei
job: Developer
name: Thomas

🔹 只要 key

for key in user.keys {
print("Key = \(key)")
}

🔹 只要 value

for value in user.values {
print("Value = \(value)")
}

🔹 搭配 enumerated()(通常用在 Array,比較少用在 Dictionary)

let fruits = ["apple", "banana", "cherry"]

for (index, fruit) in fruits.enumerated() {
print("\(index): \(fruit)")
}

👉 所以總結:

  • Dictionaryfor (key, value) in dict
  • Array / Setfor item in array

要不要我幫你寫個 Swift 的 Dictionary 跟 JavaScript Object for...in 的對照範例