Table of contents
1.
Introduction
2.
Swift guard Statement
2.1.
Syntax:
2.2.
Example: Swift Guard Statement
2.3.
Output
3.
Swift guard with multiple conditions
3.1.
Syntax:
3.2.
Example: Swift guard with multiple conditions
3.3.
Output
4.
Swift guard-let Statement
4.1.
Example: Swift guard-let Statement
4.2.
Output
5.
Swift Break Statement
5.1.
Syntax:
6.
Swift break statement with for loop.
6.1.
Syntax:
6.2.
Example: break statement with for loop
6.3.
Output
7.
Swift break statement with a while loop
7.1.
Syntax:
7.2.
Example: break statement with a while loop
7.3.
Output
8.
Swift break statement with nested loops
8.1.
Syntax:
8.2.
Example: break statement with a nested loop
8.3.
Output
9.
Frequently Asked Questions
9.1.
In Swift, what is the purpose of the guard statement?
9.2.
Why is the break statement required in a switch?
9.3.
What is the primary difference between continue and break?
10.
Conclusion
Last Updated: Mar 27, 2024
Easy

Swift Guard and Break Statement

Author Ayush Mishra
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Swift is Apple's user-friendly and powerful programming language. It will use to create apps for various platforms, including iOS, macOS, and watchOS. In this article, you'll learn some programming basics while using the Swift programming language in a modern, user-friendly environment.

We'll start with the fundamentals of the Swift language to transfer program control out of scope when certain conditions are not met and to match and ignore a particular case or break out of a matched case before that case has completed its execution; we use guard and break statements.

Let's get started with the Swift programming language's fundamental notions.

Swift guard Statement

A guard statement is as easy to use as an if-else statement, but it has advantages and uses. If one or more than one requirement isn't satisfied, a Swift guard statement will use to move program control out of scope. Alternatively, if a condition expression evaluates true, the guard statement's body is not executed.

In other words, the program's control flow does not pass through the body of the guard statement. Otherwise, the statement inside the body of the guard statement will execute if the condition evaluates false.

Syntax:

guard <condition>  else {
 // body
}

A guard statement's condition must be of the boolean type. The state might alternatively be an optional unwrap.

Expression returns either true or false in this case. If the term is equal to, then.

True - The guard code block's statements are not performed.

False -  The guard code block's statements are performed.

Example: Swift Guard Statement

var j = 1
while (j <= 15) {
    
  // guard condition to check the odd number 
  guard j % 2 != 0 else {
   
     j = j + 1
    continue
  }
  print(j)
  j = j + 1
}

Output

1
3
5
7
9
11
13
15

We used the guard statement in the last example to determine whether the value is odd or not.

Note: Control statements such as continue, break, and others must be used. Otherwise, we'll not exit the scope; consider using return and continue to exit the scope. 

Swift guard with multiple conditions

Multiple criteria separated by commas can be evaluated using guard statements (,). If at least one condition evaluates false, the guard statement's body will be performed. In other words, the body of the guard statement is not executed until and until all of the conditions are met, similar to logical AND. Otherwise, the guard statement's body will always be performed.

Syntax:

guard condition1, condition2, ….. else {
    //statement
 }

Example: Swift guard with multiple conditions

func iaseligibility() {
  var age = 17
  guard age >= 21, age < 32 else {
    print("You are not eligible.")
    return
  }
  print("If you are general category, then you are eligible")
}
iaseligibility()

Output

You are not eligible.

The logical AND relationship between two conditions will be present here. Only if both requirements are valid is the guard condition actual.

Swift guard-let Statement

When working with Swift Optionals, the guard statement is used as the guard-let statement.

Example: Swift guard-let Statement

func checkAge() {
  var age: Int? = 18
  guard let myAge = age else {
    print("You are not 18 years old")
    return
  }
  print("You are 18 years old")
}
checkAge()

Output

You are 18 years old

The code inside the guard-let block is not performed because age has some value. checkAge functions similarly to the proper guard condition.

Swift Break Statement

The break statement is a control statement used to immediately stop the execution of the full control flow statement. It simply interrupts the program's current flow when specific criteria are met. It can be used inside when you want to halt the execution of a switch or loop statement early. This phrase is typically used when we aren't sure how many iterations we want or when we want the loop to end based on a condition.

Syntax:

break

Swift break statement with for loop.

When a condition is met, we can use the break statement with the for loop to end it.

Syntax:

for items in sequence{

    // statement
     break
}

Example: break statement with for loop

for j in 1...8{
  
  if j == 4 {
    break
  } 
print(j)
}

Output

1
2
3

When j equals 4, the loop exit with the break statement, as a result, the output excludes values after 3. 

Swift break statement with a while loop

The break condition can also be used to end a while loop.

Syntax:

while (condition)
{
    // statement
    // Condition for break statement
    if (condition) 
    {
        break
    }
}

Example: break statement with a while loop

// program to find the first four multiples of 5
var j = 1
while (j<=10) {
  print("6 * \(j) =",5 * j)
    if j >= 4 {
      break
   }
  j = j + 1
}

Output

6 * 1 = 5
6 * 2 = 10
6 * 3 = 15
6 * 4 = 20

In the example, we have used the while loop to find the first four multiples of 5. When j is greater than or equal to 4, the while loop is terminated.

Swift break statement with nested loops

The break statement stops the inner loop when used with nested loops

Syntax:

// Outer for loop
for value1 in series1
{
    // Inner for loop
    for value2 in series2
    {
        // break condition
        if (condition) 
        {
            break
        }
    }
}

Example: break statement with a nested loop

// outer for loop
for i in 1...6 {
  // inner for loop
  for j in 1...3 {
    if i == 2 {
      break
    }
    print("i = \(i), j = \(j)")
  }
}

Output

i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 3, j = 1
i = 3, j = 2
i = 3, j = 3
i = 4, j = 1
i = 4, j = 2
i = 4, j = 3
i = 5, j = 1
i = 5, j = 2
i = 5, j = 3
i = 6, j = 1
i = 6, j = 2
i = 6, j = 3

In the preceding example, we utilized the break statement inside the inner for loop.

The break statement is performed when the value of i is 2. It ends the inner loop and moves the program's control flow to the outer loop.

As a result, the output never shows the value of i = 2.

Frequently Asked Questions

In Swift, what is the purpose of the guard statement?

When specific requirements are not met, the guard statement in Swift is used to shift program control out of scope.

 

Why is the break statement required in a switch?

You can use the break statement to stop the switch statement from processing a piece of specific labelled information. It follows the switch statement until the end. Without a break, the program moves on to the following designated statement and executes it until it reaches a break or the end of the

 information.

 

What is the primary difference between continue and break?

The main distinction between the break and continue statements in C is that the break statement causes the innermost switch or enclosing loop to terminate immediately. On the other hand, the continue statement starts the next iteration of the while, for, or do loop.

Conclusion

This article has thoroughly covered the concept of the break and continue statement. We began with an overview of Swift guard and break and then went over each syntax and example in detail, complete with explanations, code, and output statements.

We hope that this blog has improved your understanding of Swift loops, and if you would like to learn more, check out our blogs, the Definitive Swift Tutorial for Beginners, and why iOS & OS X Developers are choosing Swift? and which is better to learn? iOS or Android?

Happy learning!

Live masterclass