English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this article, you will learn how to use guard statements to control the flow of program execution.
Swift If StatementThis describes how to perform operations based on a specific condition (boolean value). In this article, we will learn the advantages of guard statements over if statements to control program flow and write simpler and cleaner code.
The main use of guard statements is to transfer program control outside of a certain scope under certain conditions. These statements are similar to if statements that execute statements based on a specific condition (boolean value), but unlike if, guard statements only run when certain conditions are not met.
In addition, the guard statement must exit the scope. Therefore, we must use user program control statements return, break, continue, or throw at the end of the guard statement.
guard expression else { //Statement //A control statement must be included: return, break, continue, or throw. }
Here, expression is a boolean expression (returns true or false).
If the value of expression is calculated as false, the guard statement inside the code block will be executed.
If the value of expression is calculated as true, the guard statement inside the code block will skip the execution.
Note: The end of the guard statement must include a control statement return, break, continue, or throw.
A simple valid guard statement is as follows:
guard true else { print("Condition not met") } print("Condition met")
When running the program, the output is:
Condition met
In the above program, guard contains a boolean value true (condition met). Since the guard statement only runs when the condition is not met, the statements inside the guard will not be executed. This is why print("Condition met") is executed and output to the screenCondition met.
Now, change the condition to false:
guard false else { print("Condition not met") } print("Condition met")
In the above program, the calculation result of the guard condition is false. Therefore, the print("Condition not met") statement in the else block should be executed. However, you will receive an error message:'guard' body may not fall through, consider using a 'return' or 'throw' to exit the scope.
The error message means that you need to use return, break, continue, or throw statements to transfer program control from the guard statement. Now we will use return. Since the return statement can only be used inside a function, we will wrap the above code inside a Swift function.
We can use the guard statement in Swift'sInside the functionThe guard statement can be used as follows:
func someFunction() { guard false else { print("Condition not met") return } print("Condition met") } someFunction() print("Hello is output after the function call")
When you run the above program, the output will be:
Condition not met Hello is output after the function call.
In the above program, the calculation result of the guard condition is false, therefore, the statements inside the guard are executed. The first statement print("Condition not met") is output to the console.Condition not met.
And the statement return terminates the execution of the function, while the statement print("Hello, after function call") outputs the following after the function call:Function call output Hello.
We areIn Swift OptionalsWe have already seen using if-Using let to unwrap an Optional. But we can also use guard statements instead of if-Using let to expand optional statements has the benefit. Using guard instead of if-The main advantage of unwrapping optional variables with let is that we can increase the scope of the unwrapped variable.
Let's see this in the following example:
func changeOptionalStringToUpperCase() { var name: String? guard let temp = name else { print("The name is nil. Cannot be processed") return } print("Uppercase: (temp.uppercased())") } changeOptionalStringToUpperCase()
When you run the above program, the output will be:
The name is nil. Cannot be processed
In the above program, you can see that the unwrapped value temp is used outside the scope defined by the guard statement. Since name is defined as optional and contains a nil value, the guard statement cannot unwrap this value.
Therefore, the statement printing "Name is nil. Cannot be processed" and the return statement terminating the function are executed in the guard else. The equivalent code for the above guard statement and if else statement is:
func changeOptionalStringToUpperCase() { var name: String? if let temp = name { print("Uppercase: (temp.uppercased())") } print("The name is nil. Cannot be processed") return } //How to access it here? Solution: Use Guard } changeOptionalStringToUpperCase()
Note that the two statements above are valid and perform the same work. However, using if-You cannot use let statements within an if-Using unwrapped (unwrapped) values outside of let statements. However, with guard statements, you can use unwrapped values within a function.
Guard statements can link multiple conditions, separated by commas (,), as shown below:
func changeOptionalStringToUpperCase() { var name: String? = "" guard let temp = name, temp.count > 0 else { print("The name is nil or an empty string. Cannot be processed") return } print("Uppercased:\(temp.uppercased())") } changeOptionalStringToUpperCase()
When you run the above program, the output will be:
Name is nil or an empty string. Cannot be processed
In the above program, the guard statement contains two conditions separated by a comma.
The first condition let temp = name unwraps an optional parameter, in our instance, this condition returns true, the second condition temp.count > 0 checks if the string unwrapped is longer than 0 characters, in our example the result is false.
Therefore, the statements inside the guard statement are executed print("Name is nil or an empty string. Cannot be processed") Its output Name is nil or an empty string. It cannot be processed in the console and the function is terminated using the return statement.