Swift Break Statement

  Total Views : 335
  Comments : 0
  Keywords : Swift break statement to exit current loop or switch case statement with examples, Swift break statement to reach end of the loop with examples

Here we will learn break statement in swift with examples and how to use swift break statement to exit or break current iteration of loop or switch case statements with examples.

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 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 above code in 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.

 Comments (0)

Be the first to give your valuable feedback

Leave a comment

  • Default Tutlane User