Continue and Break
In for-loops and while-loops, the continue
statement can be used to stop the current iteration of a loop and start the next iteration.
var i = 0
var x = 0
while i < 10 {
i = i + 1
if i < 3 {
continue
}
x = x + 1
}
// `x` is `8`
let array = [2, 2, 3]
var sum = 0
for element in array {
if element == 2 {
continue
}
sum = sum + element
}
// `sum` is `3`
The break
statement can be used to stop the execution of a for-loop or a while-loop.
var x = 0
while x < 10 {
x = x + 1
if x == 5 {
break
}
}
// `x` is `5`
let array = [1, 2, 3]
var sum = 0
for element in array {
if element == 2 {
break
}
sum = sum + element
}
// `sum` is `1`
Last updated
Was this helpful?