โ 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 labeledbreak 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`
}
// ------------ 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]