O'Reilly logo

Mastering Swift 4 - Fourth Edition by Jon Hoffman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The break statement

The break statement immediately ends the execution of a code block within the control flow. The following example shows how to break out of a for-in loop when we encounter the first even number:

for i in 1...10 {  
  if i % 2 == 0 { 
    break 
  } 
  print("\(i) is odd") 
} 

In the preceding example, we loop through the range of 1 through 10. For each iteration of the for-in loop, we use the remainder (%) operator to see whether the number is odd or even. If the number is even, we use the break statement to immediately exit the loop. If the number is odd, we print out that the number is odd, and then go to the next iteration of the loop. The preceding code has the following output:

1 is odd 

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required