Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is a guard statement in Swift?
In this tutorial, you will learn about what is a guard statement and how it is implemented in the Swift language. Let's learn.
What is a guard statement?
In Swift, the guard is a statement that transfers control between codes like an if-else statement. The guard statement is the most commonly used statement in Swift. When certain conditions are not met to allow the flow to continue, the guard statement is used to transfer flow control.
A guard statement is similar to an if statement with one major difference. The if statement runs when a certain condition is met. However, the guard statement runs when a certain condition is not met.
Syntax
guard expression else {
// other statements
// control statement: return, break, continue or throw.
}
In the above syntax, the expression returns either true or false. If the expression evaluates to
true ? guard does not execute statements inside its code block
false ? guard executes statements inside its code block
Note ? It is mandatory to use return, break, continue or throw to exit the guard scope.
Example
<div class="execute"></div><div class="code-mirror language-javascript" contenteditable="plaintext-only" spellcheck="false" style="outline: none; overflow-wrap: break-word; overflow-y: auto; white-space: pre-wrap;"><span class="token keyword">var</span> i <span class="token operator">=</span> <span class="token number">2</span>
<span class="token keyword">while</span> <span class="token punctuation">(</span>i <span class="token operator"><=</span> <span class="token number">10</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
<span class="token comment">// check the even number</span>
guard i <span class="token operator">%</span> <span class="token number">2</span> <span class="token operator">==</span> <span class="token number">0</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
i <span class="token operator">=</span> i <span class="token operator">+</span> <span class="token number">1</span>
<span class="token keyword">continue</span>
<span class="token punctuation">}</span>
<span class="token function">print</span><span class="token punctuation">(</span>i<span class="token punctuation">)</span>
i <span class="token operator">=</span> i <span class="token operator">+</span> <span class="token number">1</span>
<span class="token punctuation">}</span>
</div><div class="output-wrapper"><div class="console-close"></div><div class="code-output"></div></div>
Output
2 4 6 8 10
Guard statement to unwrap the optional value
In Swift, you can unwrap a value from an optional variable like the below ?
Example
<div class="execute"></div><div class="code-mirror language-javascript" contenteditable="plaintext-only" spellcheck="false" style="outline: none; overflow-wrap: break-word; overflow-y: auto; white-space: pre-wrap;">func <span class="token function">doSomething</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
<span class="token keyword">let</span> name<span class="token operator">:</span> String<span class="token operator">?</span> <span class="token operator">=</span> <span class="token string">"Amit Saxena"</span>
guard <span class="token keyword">let</span> nameString <span class="token operator">=</span> name <span class="token keyword">else</span> <span class="token punctuation">{</span>
<span class="token function">print</span><span class="token punctuation">(</span><span class="token string">"name is not found"</span><span class="token punctuation">)</span>
<span class="token keyword">return</span>
<span class="token punctuation">}</span>
<span class="token function">print</span><span class="token punctuation">(</span><span class="token string">"Name found: \(nameString)"</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>
<span class="token function">doSomething</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
</div><div class="output-wrapper"><div class="console-close"></div><div class="code-output"></div></div>
Output
Name found: Amit Saxena
Guard statement with multiple conditions
Syntax
guard condition1, condition2, conditionN else {
// statements
return
}
The guard statement can be used to check for multiple conditions. If all conditions are met, further code will be executed, otherwise, the guard's body will be executed and returned.
Example
<div class="execute"></div><div class="code-mirror language-javascript" contenteditable="plaintext-only" spellcheck="false" style="outline: none; overflow-wrap: break-word; overflow-y: auto; white-space: pre-wrap;"><span class="token keyword">class</span> <span class="token class-name">Student</span> <span class="token punctuation">{</span>
<span class="token keyword">var</span> name<span class="token operator">:</span> String<span class="token operator">?</span>
<span class="token keyword">var</span> age<span class="token operator">:</span> Int<span class="token operator">?</span>
<span class="token keyword">var</span> address<span class="token operator">:</span> String<span class="token operator">?</span>
func <span class="token function">allDataValid</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">-</span><span class="token operator">></span> Bool <span class="token punctuation">{</span>
guard <span class="token keyword">let</span> nameString <span class="token operator">=</span> name<span class="token punctuation">,</span> <span class="token keyword">let</span> age <span class="token operator">=</span> age<span class="token punctuation">,</span> <span class="token keyword">let</span> address <span class="token operator">=</span> address <span class="token keyword">else</span> <span class="token punctuation">{</span>
<span class="token function">print</span><span class="token punctuation">(</span><span class="token string">"some data is not valid."</span><span class="token punctuation">)</span>
<span class="token keyword">return</span> <span class="token boolean">false</span>
<span class="token punctuation">}</span>
<span class="token function">print</span><span class="token punctuation">(</span><span class="token string">"Name: \(nameString), age: \(age), address: \(address)"</span><span class="token punctuation">)</span>
<span class="token keyword">return</span> <span class="token boolean">true</span>
<span class="token punctuation">}</span>
<span class="token punctuation">}</span>
<span class="token keyword">let</span> amit <span class="token operator">=</span> <span class="token function">Student</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token function">print</span><span class="token punctuation">(</span>amit<span class="token punctuation">.</span><span class="token function">allDataValid</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
</div><div class="output-wrapper"><div class="console-close"></div><div class="code-output"></div></div>
Output
some data is not valid. false
Guard with an Enum Case
Enumeration cases can also be matched using the guard statement. You can use the guard to check if an enumeration object matches the desired case.
Example
<div class="execute"></div><div class="code-mirror language-javascript" contenteditable="plaintext-only" spellcheck="false" style="outline: none; overflow-wrap: break-word; overflow-y: auto; white-space: pre-wrap;"><span class="token keyword">enum</span> ErrorState <span class="token punctuation">{</span>
<span class="token keyword">case</span> noInternet
<span class="token keyword">case</span> serverNotReachable
<span class="token keyword">case</span> somethingWrong
<span class="token keyword">case</span> none
<span class="token punctuation">}</span>
func <span class="token function">perform</span><span class="token punctuation">(</span><span class="token parameter">state<span class="token operator">:</span> ErrorState</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
guard <span class="token keyword">case</span> state <span class="token operator">=</span> ErrorState<span class="token punctuation">.</span>none <span class="token keyword">else</span> <span class="token punctuation">{</span>
<span class="token function">print</span><span class="token punctuation">(</span><span class="token string">"Some error found, cannot execute further code."</span><span class="token punctuation">)</span>
<span class="token keyword">return</span>
<span class="token punctuation">}</span>
<span class="token function">print</span><span class="token punctuation">(</span><span class="token string">"No error found"</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>
<span class="token function">perform</span><span class="token punctuation">(</span>state<span class="token operator">:</span> ErrorState<span class="token punctuation">.</span>serverNotReachable<span class="token punctuation">)</span>
</div><div class="output-wrapper"><div class="console-close"></div><div class="code-output"></div></div>
Output
Some error found, cannot execute further code.
Explanation
In the above example, we have created an enum for ErrorState with different cases. Now in the perform() function, we are checking for an error state using an enum case and returning if any error is found other than none case. You can see how flexible the guard statement can be to check different conditions.
Benefits of using Guard Statement in Swift
The guard statement is very useful in making your code readable and maintainable. There are some reasons why you should use the guard statement ?
It becomes clear what the code is trying to accomplish. Instead of telling the guard what you don't want, you can tell him directly what you want.
The function should be able to detect invalid arguments.
Make unwrapped values usable by unwrapping optionals with the guard.
Reduce the number of lines of code.
Conclusion
The guard statement in Swift was explained to you. When certain situations arise, the guard statement solves the issue of code readability. With a guard, a piece of code could be written in a clean manner. Further, you can learn about other statements like if-else, switch, etc.
