๐ŸŽ“ A1Learner
๐Ÿ”

Swift Break and Continue

Break and continue are loop statements that cut a pass short in two different ways. One stops the loop for good and the other skips a single pass.

Break stops a search at the target

The loop checks each value in the list in order. A check counter shows how many values got checked before the stop.

var checks = 0
for value in [4, 8, 15, 16, 23] {
    checks += 1
    if value == 15 {
        print(value)
        break
    }
}
print(checks)

Continue skips the even numbers

Continue sends each even pass straight to the next number. Only the odd numbers reach the print line.

for number in 1...6 {
    if number % 2 == 0 {
        continue
    }
    print(number)
}

Break can end a while loop early

The while check alone would allow ten passes. Break ends the loop as soon as the counter hits 3.

var count = 0
while count < 10 {
    count += 1
    if count == 3 {
        break
    }
}
print(count)

Example

var checks = 0
for number in 1...8 {
    if number % 2 == 0 {
        continue
    }
    checks += 1
    if number == 7 {
        break
    }
}
print(checks)

Key points

  • A break ends the looping at once, and a continue ends only the current pass.
  • After a break runs, the code after the loop runs next.
  • After a continue runs, the rest of that pass is left undone.
  • A condition inside the body decides the pass in which break or continue runs.

In this example, the first line sets checks to 0. The loop walks the numbers 1 through 8, and continue skips each even number without counting it. Each odd number adds 1 to checks, so 1, 3 and 5 bring the count to 3. At 7 the count reaches 4 and break ends the loop, and the last line prints checks as 4.

Note

The remainder test number % 2 == 0 is true exactly for even numbers.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz Swift Compiler

Exercise

A loop prints only the odd numbers from 1 to 6, skipping the evens with continue. What prints on the last line?