Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Using break & continue in Loops
Written by Team Kodeco

The break and continue keywords help you control the flow of loops in Swift.

Using the break Keyword

The break keyword allows you to exit a loop early. It can be used to exit a for, while, or repeat-while loop. Here’s an example of using break to exit a for loop:

for i in 1...10 {
  if i == 5 {
    // exit the loop when i is equal to 5
    break
  }
  print(i, terminator: " ")
}
// 1 2 3 4

In this example, the for loop iterates through the range 1…10. When the value of i is equal to 5, the break statement is executed and the loop is exited. As a result, the numbers 1 through 4 are printed, but 5 is not.

Using the continue Keyword

The continue keyword allows you to skip the current iteration of a loop and move on to the next iteration. It can be used in a for, while, or repeat-while loop. Here’s an example of using continue to skip even numbers in a for loop:

for i in 1...10 {
  if i % 2 == 0 {
    // skip even numbers
    continue
  }
  print(i, terminator: " ")
}
// Output: 1 3 5 7 9

In this example, the for loop iterates through the range 1…10. For each iteration, the value of i is checked to see if it’s even. If it is, the continue statement is executed and the current iteration is skipped. As a result, only the odd numbers in the range 1…10 are printed.

© 2024 Kodeco Inc.