🔰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`
}
Last updated
Was this helpful?