Guard Statement in Swift 5 with Examples – Ultimate Guide

By | June 25, 2019

Guard Statements were first introduced in Swift 2. In the first glance, they look very much like an if-else statement. But they were introduced to tackle a condition in which, we can only proceed if a certain condition turns out to be true. Its second use case is Optional Unwrapping and they are slightly different from Conditional Unwrapping (if-let statements).

guard-statement-swift-5

Guard Statement Syntax

guard condition else {
     //Any transfer control statement like return fatalError etc
     return
 }

Here
– The condition can be any expression which results in a Boolean Value. If the condition is true then the control will shift to the next statements. Otherwise, else block will get executed and the control should go out of the current scope.

– Generally, we use a return statement in the else block. But we can also use, break continue (if its inside a loop) or fatalError() to get out of the current scope of the function.

Also Read – Local Repository is out of date Xcode

Validation with Guard

It’s a very common scenario when we need certain conditions turns out to be true, only then we can continue the execution of the function or even the whole program. guard statement in Swift 5 comes handy for such purposes.

Let’s take an example of that. Let’s say we want 10 digit mobile number, to make an API call for login. In our case, we should not even make an API call, if the number count is not exactly 10. We will use guard statement in this case.

func validateMobileNo(mobileNo: String){
	guard mobileNo.count == 10 else {
		//exiting function in case the count is not 10
		return
	}

	// Making API call only when there is 10 digit mobileNo
	makeAPICall(with: mobileNo)
}

Important Note for Guard statement in iOS Swift

If you are using guard statement, then it is mandatory to write a Control Transfer statement in else block like (return, throw, fatalError(), break, etc). Otherwise, it will result in an error.

Unwrapping Optionals with Guard

Optionals is one of the core concepts of Swift. Swift has provided multiple methods to deal with unwrapping of optionals. Each method has its own advantage and its disadvantage.
Guard statements are used to unwrap optionals and they provide alternate solution for conditional unwrapping (if – let statements).

When should we use guard over if – let ?

One main disadvantage of using conditional unwrapping is that the unwrapped value can’t be accessed outside its scope. Take a look inside the below code.

func testingConditionalBinding(){
	var usersOnline : String?
	usersOnline = "10"

	if let onlineUsers = usersOnline {
		print("Online users are \(onlineUsers)")
		sendOnlineUsers(with: onlineUsers)
	}
	else {
		// It will be executed when usersOnline has nil value
		print("There are no users Online!")
	}
}

By using the above approach, we can only access the unwrapped value within the scope of if – let statement only and we are calling another function with there itself.

This approach is not good if we want to use that unwrapped value several times for other computations. With guard statement, we can access the unwrapped value within the scope of the function itself. Let’s unwrap the same value using guard statement.

func testingGuardStatement(){
	var usersOnline : String?
	usersOnline = "10"

	guard let onlineUsers = usersOnline else {
		// It will get executed if usersOnline is nil
		// It should have control transfer statement like return
		print("There are no users Online!")
		return
	} 

	print("Online users are \(onlineUsers)")
	sendOnlineUsers(with: onlineUsers)
}

Validation Testing with guard in Swift 5

One most common use case of guard is while testing the credentials during Login. We need to validate the username for certain conditions. If it turns out to be false, then there is no point in making API calls with that value.
Here we will use Swift guard to validate our username.

where clause – We use it to validate the unwrapped value. So, the code execution will continue only if the value is non-nil and it turns the supplied condition to true.

func validationWithGuard(userName: String?){
	guard let actualUser = userName where actualUser.count > 5 &amp;&amp; actualUser.count < 8 else {
		// It will get executed if userName is nil
		// It will also get execute if value of userName has less than 5 or greater than 8 characters
		print("Invalid userName!")
		return
	} 

	loginUsingUsername(with: actualUser)
}

In the above code, the code exceution will only continue, when optional does not have a nil value and it should pass the condition inside where clause as well.

If we need to check multiple conditions then it is recommended to use separate functions or extension to test those conditions. Otherwise, it will decrease the readability of the code.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.