๐Ÿ”ฐfor...in vs. forEach

Swift โŸฉ flow control โŸฉ loop โŸฉ for...in vs. .forEach()

flow controlfor ... 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.

โ›” error: return invalid outside of a func.

for n in 1...10 {
    if n == 3 { return }    // โ›” error
    //          ^^^^^^
    // โ›” error: return invalid outside of a func
}

โ›” error: continue is only allowed inside a loop.

(1...10).forEach { n in 
    if n > 2 { continue }    // โญ `continue` is inside a closureโ—
    //         ^^^^^^^^
    // โ›” error: 'continue' is only allowed inside a loop
}

โ›” error: unlabeled break is only allowed inside a loop or switch, a labeled break is required to exit an if or do.

(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