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 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset