🔰for...in vs. forEach

Swiftflow controlloop ⟩ for...in vs. .forEach()

flow control
for ... in
.forEach()

continue

✅ skip to the next iteration.

⛔ not allowed

break

✅ break the iteration completely.

⛔ not allowed

invalid outside of a function.

❗skip to the next iteration.

for n in 1...10 {
    if n == 3 { return }    // ⛔ error
    //          ^^^^^^
    // ⛔ error: return invalid outside of a func
}
(1...10).forEach { n in 
    if n > 2 { continue }    // ⭐ `continue` is inside a closure❗
    //         ^^^^^^^^
    // ⛔ error: 'continue' is only allowed inside a loop
}
(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?