What is the use of break statement in Swift language?

The break statement is used within a loop where you have to immediately terminate a statement. It is also used to terminate a case in switch statement.

In Swift, the break statement is used to exit or terminate the execution of a loop, switch statement, or labeled statement prematurely. Here’s how it works in different contexts:

  1. Loop: Inside a loop (like for, while, or repeat-while), break is used to immediately exit the loop and resume execution at the next statement following the loop.
for i in 1...10 {
if i == 5 {
break // exits the loop when i equals 5
}
print(i)
}
// Output: 1 2 3 4
  1. Switch Statement: In a switch statement, break is used to exit the switch statement once a matching case is found. Without break, execution continues to subsequent cases.

let direction = "north"

switch direction {
case “north”:
print(“Heading north”)
break // exits the switch statement
case “south”:
print(“Heading south”)
default:
print(“Heading elsewhere”)
}
// Output: Heading north

  1. Labeled Statements: break can also be used with labeled statements to break out of nested loops or switch statements.
outerLoop: for i in 1...3 {
for j in 1...3 {
if i * j == 6 {
print("The product is 6.")
break outerLoop // exits both loops when product is 6
}
print("\(i) * \(j) = \(i * j)")
}
}
// Output:
// 1 * 1 = 1
// 1 * 2 = 2
// 1 * 3 = 3
// 2 * 1 = 2
// 2 * 2 = 4
// 2 * 3 = 6
// The product is 6.

So, in essence, the break statement in Swift provides a means to exit out of control flow structures prematurely, providing more flexibility and control over program execution.