🔰for...in vs. forEach
Swift ⟩ flow control ⟩ loop ⟩ for...in vs. .forEach()
flow control
for ... in
.forEach()
continue
✅ skip to the next iteration.
⛔ not allowed
break
✅ break the iteration completely.
⛔ not allowed
👉 replit
⛔ error: return invalid outside of a func.
for n in 1...10 {
if n == 3 { return } // ⛔ error
// ^^^^^^
// ⛔ error: return invalid outside of a func
}👉 replit
(1...10).forEach { n in
if n > 2 { continue } // ⭐ `continue` is inside a closure❗
// ^^^^^^^^
// ⛔ error: 'continue' is only allowed inside a loop
}👉 replit
(1...10).forEach { n in
if n > 2 { break } // ⭐ `break` is inside a "closure"
// ^^^^^
// ⛔ error:
// • unlabeled 'break' is only allowed inside a loop or switch
// • labeled 'break' is required to exit an `if` or `do`
}👉 replit
// ------------ for...in ------------------------------
for n in 1...10 {
if n == 3 { continue } // ⭐ skip to next iteration
if n > 6 { break } // ⭐ break loop completely❗
a1.append(n) // [1, 2, 4, 5, 6]
}
// ------------ .forEach ------------------------------
(1...10).forEach { n in
if n > 2 { return } // ⭐ early return ( skip to next iteration❗)
a2.append(n) // [1, 2] (n > 2 NOT appended)
}
(1...10).forEach { n in
a3.append(n) // ⭐ number appended
if n > 2 { return } // ⭐ late return ( has no effect❗)
} // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]Last updated
Was this helpful?