Swift Break Statement

In Swift, the break statement is used to exit a loop or a switch case statement early. It can be used in a for loop, while loop, repeat-while loop, and a switch statement.

Using Break in Loops

In a loop, the break statement is used to exit the loop before it has reached its end. This can be useful if you need to terminate the loop early based on a certain condition. Here is an example:

1for number in 1...10 { 2 if number == 5 { 3 break 4 } 5 print(number) 6}

Output:

11 22 33 44

In the above example, the for loop iterates from 1 to 10. When the value of number is equal to 5, the break statement is executed, and the loop is terminated early. As a result, the output shows only the numbers 1 through 4.

The break statement can also be used in a while loop or repeat-while loop in a similar manner.

Using Break in a Switch Statement

In a switch statement, the break statement is used to exit the switch block early. This is necessary because unlike other languages, Swift does not automatically exit the switch block after a matching case statement is executed. Here is an example:

1let number = 3 2 3switch number { 4case 1: 5 print("One") 6case 2: 7 print("Two") 8case 3: 9 print("Three") 10 break 11case 4: 12 print("Four") 13default: 14 print("Unknown") 15}

Output: Three

In the above example, the switch statement is used to check the value of the constant number. When number is equal to 3, the third case statement is executed, and the break statement is used to exit the switch block early. As a result, only the string "Three" is printed to the console.

The break statement is a powerful tool for controlling the flow of a program in Swift. It can be used to terminate loops early or to exit a switch statement after a matching case has been found. By using break strategically, you can make your code more efficient and easier to understand.