Swift programming for Beginners – Swift break Statement

(Swift for Beginners)

Swift break Statement

In this article, you will learn to use break statement to transfer control of the program.

When you are working with loops or conditional statements, you may require to skip some statements inside the loop or terminate the loop immediately without checking the test expression

In such cases, break and continue statements are used. You will learn about continue statement in the next chapter.

The break statement stops the execution of a loop or a switch statement. It then jumps to the next statement following the loop or switch statement.

 

The syntax of a break statement is:

break

How break statement works?

Swift break statement

Example 1: Swift break statement in for loop

for i in 1...5 {
    if i == 4 {
        break
    }
    print("i = (i)")
}
print("The end")

When you run the program, the output will be:

i = 1
i = 2
i = 3
The end

In the above program, the sequence being iterated over is a range from 1 to 5.

The value of i is set to the first number in the range (1), and updated to the next number of the range on each iteration.

The loop also contains an if statement with expression i == 4 . The expression when evaluated to true (on 4th iteration) executes the break statement and the for-in loop terminates.

It then jumps outside the loop to print The end.


Example 2: Swift break statement in while loop

var currentLevel:Int = 1, finalLevel:Int = 2
var isLifeAvailable = true
while (isLifeAvailable) {
    
    if currentLevel > finalLevel {
        print("Game Completed. No level remaining")
        break
    }
    //play game and go to next level
    currentLevel += 1
    print("next level")
}
print("outside of while loop")

When you run the program,the output will be:

next level
next level
Game Completed. No level remaining
outside of while loop

In the above program, the test expression of the while loop is always true.

When the currentLevel is greater than finalLevelbreak statement inside the if block is executed. The program then breaks out of (terminates) the while loop and executes the statements after the loop, i.e. print("outside of while loop")..


Example 3: Swift break statement with nested loops

for j in 1...2 {
    for i in 1...5 {
        if i == 4 {
            break
        }
        print("i = (i)")
    }
    print("j = (j)")
}

When you run the program,the output will be:

i = 1
i = 2
i = 3
j = 1
i = 1
i = 2
i = 3
j = 2

In the above program, break statement inside the if i == 4 only terminates the execution of the inner loop for i in 1...5. However, it continues the execution of the outer loop for j in 1...2.

But what if you want to break the outerloop for j in 1...2 as well. For that, we use labeled statements in Swift.


Labeled Statement with break

Statements that have prefixes in the form (label : Statement) are called as labeled statement. The label is an identifier which you can refer later in the break or continue statements. To learn more about labeled statements, visit Swift labeled statement.

How labeled statement with break works?

labeled statement witb break

Here, label is an identifier. When break statement executes, it terminates the loops inside the label, and the program jumps to the statement immediately following the labeled statement.

Example 4: Labeled Statement with break

outerloop: for j in 1...2{
    innerloop: for i in 1...5 {
        if i == 4 {
            break outerloop
        }
        print("i = (i)")
    }
    print("j = (j)")
}

When you run the program, the output will be:

i = 1
i = 2
i = 3

In the above program, there are two labeled statements outerloop: for j in 1...2 and innerloop: for i in 1...5.

The label names outerloop and innerloop can be used with the break statement.

The statement break outerloop terminates both the loops and ends the program.

If you are familiar with other programming language like C, C++, Java, etc, break statement is used to terminate switch statement. But in Swift, switch statement finishes its execution as soon as the first matching switch case is completed. Therefore, it’s optional to add break at the switch case in Swift. To learn more, visit Swift switch statement.

 

 

Swift programming for Beginners – Swift break Statement

 

Personal Career & Learning Guide for Data Analyst, Data Engineer and Data Scientist

Applied Machine Learning & Data Science Projects and Coding Recipes for Beginners

A list of FREE programming examples together with eTutorials & eBooks @ SETScholars

95% Discount on “Projects & Recipes, tutorials, ebooks”

Projects and Coding Recipes, eTutorials and eBooks: The best All-in-One resources for Data Analyst, Data Scientist, Machine Learning Engineer and Software Developer

Topics included: Classification, Clustering, Regression, Forecasting, Algorithms, Data Structures, Data Analytics & Data Science, Deep Learning, Machine Learning, Programming Languages and Software Tools & Packages.
(Discount is valid for limited time only)

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.

Learn by Coding: v-Tutorials on Applied Machine Learning and Data Science for Beginners

Please do not waste your valuable time by watching videos, rather use end-to-end (Python and R) recipes from Professional Data Scientists to practice coding, and land the most demandable jobs in the fields of Predictive analytics & AI (Machine Learning and Data Science).

The objective is to guide the developers & analysts to “Learn how to Code” for Applied AI using end-to-end coding solutions, and unlock the world of opportunities!