Swift Break Statement

In swift, break statement will stop or ends execution of current flow statements immediately. We can use break statement within switch case statement or loops to exit or end execution of loops or switch statements based on our requirements.

Syntax of Swift Break Statement

Following is the syntax of break statement in swift programming language.

 

break

Now we will see how to use break statement in swift programming language with examples.

Swift Break Statement in Switch Case

In swift if we use break statement in switch case statement immediately it will break or end switch case and code execution will come out of switch case statement.

 

Following is the example of using break statement in a swift case statement.

 

func Year(year: Int) -> Bool {

switch (year) {

case let number where (number % 200) == 0 && (number % 500) != 0:

break

case let number where (number % 5) == 0:

return true

default:

break

}

return false

}

print(Year(2014))

print(Year(2000))

print(Year(1900))

If you observe above example it will break or exit switch case statement immediately whenever the given condition satisfied.

 

When we run above code in swift playground we will get the result like as shown below.

 

False

True

True

Swift Break Statement in For Loop

In swift, if we use break statement within a loop then it will stop or end loop execution immediately and code execution will come out of the loop. 

 

Following is the example of using break statement in swift for loop.

 

for i in 40...50 {

if (i >= 45 && i <= 50){

break

}

print(i)

}

If you observe above example it will break or exit for loop whenever the value of “i” greater than or equal to 45.

 

When we run the above code in the swift playground we will get the result like as shown below.

 

40

41

42

43

44

This is how we can use break statement in swift programming language to exit or break the execution of complete loop or switch-case statements execution based on our requirements.