in , ,

Swift guard Statement

Swift guard Statement
Swift guard Statement

Swift guard Statement: In this tutorial, we will gain proficiency with the use of a guard statement to control the flow of your program’s execution.

Swift Guard statement is used as a substitute for Swift if statement. Guard statement provides benefits over if statement to control the program flow and write basic and clean code.

In Swift, we use the guard statement to move program control out of scope when certain conditions are not met.

The guard statement is like the if statement with one significant difference. The if statement runs when a specific condition is met. Be that as it may, the guard statement runs when a specific condition isn’t met.


Syntax of guard Statement

The syntax of the guard statement is:

guard expression else {
  // statements
  // control statement: return, break, continue or throw.
}

Here, expression returns either true or false. On the off chance that the expression assesses to

  • true- statements inside the code block of guard are not executed
  • false- statements inside the code block of guard are executed

Note: We should use return, break, continue or throw to exit from the guard scope.


Working of Swift guard Statement


Example: Swift Guard Statement

var i = 2

while (i <= 10) {
    
  // guard condition to check the even number 
  guard i % 2 == 0 else {
   
     i = i + 1
    continue
  }

  print(i)
  i = i + 1
} 

Output

2
4
6
8
10

In the above example, we have used the guard statement to check if the number is even or odd. Notice the line,

guard i % 2 == 0 else {...}

Here, in the event that I is

  • odd – , I % 2== 0 assesses to false. Furthermore, the code inside the guard is executed.
  • even – , I % 2 == 0 assesses to true. Also, the code inside the guard is skipped.

Subsequently, we just get the even numbers as our output.

We have used the continue statement inside guard to move the control to the next iteration of the loop.

Note: The use of control statements like continue, break, and so forth is compulsory. Else, we will get an error: ‘guard’ body should not fail to work out, consider using a ‘continue’ or ‘return’ to exit the scope


guard Statement Inside a Function

The guard statement is by and large used with functions. A function is a block of code that plays out a particular assignment.

Let’s see how we can use a guard statement with functions.

// create a function
func checkOddEven() {
  var number = 23

  // use of guard statement
  guard number % 2 == 0 else {
    
    print("Odd Number")
    return
  }

  print("Even Number")
}

// function call
checkOddEven()

Output

Odd Number

In the above example, we have created a function named checkOddEven(). Notice the use of guard statement inside the function.

guard number % 2 == 0 else {
    
  print("Odd Number")
  return
}

Here, the guard statement checks if the number is even or odd. Since the number is odd, the condition number % 2 == 0 returns false.

Consequently, the code inside the guard statement is executed.

Presently, let’s change the value of number to an even number, say 24.

// create a function
func checkOddEven() {
  var number = 24

  // use of guard statement
  guard number % 2 == 0 else {
    
    print("Odd Number")
    return
  }

  print("Even Number")
}

// function call
checkOddEven()

Output

Even Number

Here, since the number is even, the condition number % 2 == 0 assesses to true.

Thus, the code inside the guard statement is skipped and the other code within the function is executed. Henceforth, we get Even Number as an output


guard with multiple conditions

guard statements can likewise chain numerous conditions separated by comma (,) as:

func checkJobEligibility() {
    
  var age = 33

  guard age >= 18, age <= 40 else {
    print("Not Eligible for Job")
    return
  }

  print("You are eligible for this job")

}

checkJobEligibility()

Output

You are eligible for this job

In the above example, the guard statement contains two conditions separated by a comma.

Here, there will be the Logical AND relation between two conditions. That is, the guard condition is true just if the two conditions are true.


guard-let Statement

While working with Swift Optionals, the guard statement is used as the guard-let statement. For instance,

func checkAge() {
	
  var age: Int? = 22

  guard let myAge = age else {
    print("Age is undefined")
    return
  }

  print("My age is \(myAge)")
}

checkAge()

Output

My age is 22

In the above example, we have created an optional variable named age. Here, we are using the guard-let statement to check if age contains a value or not.

Since age contains some value, the code inside the guard-let block isn’t executed. This works like the condition of guard being true.


guard Vs if Statement

The guard statement is acquainted as an option with the if statement. For instance,

Assume we need to check if an individual is eligible to vote, we can use the if statement as:

func voteEligibility() {
    
  var age = 42

  if age >= 18 {
  print("Eligible to vote")
  }
  else {
  print("Not eligible to vote")
  }

}

voteEligibility()

Output

Eligible to vote

This equivalent program can be written using the guard statement as:

func voteEligibility() {
    
  var age = 42

  guard age >= 18 else {
  print("Not Eligible to vote")
  return
  }

  print("Eligible to vote")
}

voteEligibility()

Output

Eligible to vote

As should be obvious, with the guard statement, we can exit from the function when the condition evaluates to false.


Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.

salman khan

Written by worldofitech

Leave a Reply

Swift Continue Statement

Swift Continue Statement

Swift Arrays

Swift Arrays