Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple conditions in guard statement in Swift

Tags:

swift

Is there a way to include multiple conditions in a guard statement of Swift?

For example, if I want to check two optional values are nil using a guard, how should I do it using single guard statement?

like image 225
Kishoretheju Avatar asked Aug 29 '16 04:08

Kishoretheju


People also ask

How do guard statements work in Swift?

In Swift, we use the guard statement to transfer program control out of scope when certain conditions are not met. The guard statement is similar to the 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.

What is a guard statement?

Regardless of which programming language is used, a guard clause, guard code, or guard statement, is a check of integrity preconditions used to avoid errors during execution. A typical example is checking that a reference about to be processed is not null, which avoids null-pointer failures.

What is a guard let in Swift?

Swift gives us an alternative to if let called guard let , which also unwraps optionals if they contain a value, but works slightly differently: guard let is designed to exit the current function, loop, or condition if the check fails, so any values you unwrap using it will stay around after the check.

What is difference between if and guard in Swift?

In if let , the defined let variables are available within the scope of that if condition but not in else condition or even below that. In guard let , the defined let variables are not available in the else condition but after that, it's available throughout till the function ends or anything.


2 Answers

Check this code

func demo(){      var str = [String: String]()      str["status"] = "blue"     str["asd"] = nil      guard let var2 = str["asd"], let var1 = str["status"]     else     {         print("asdsfddffgdfgdfga")         return     }     print("asdasdasd") } 

Guard will check one by one condition. If the first is true then it will check the next. Otherwise, it will execute the else part.

like image 119
Rutvik Kanbargi Avatar answered Sep 16 '22 16:09

Rutvik Kanbargi


To answer Prabhav's question, yes, you are correct, each condition in a guard statement must be true in order to proceed (i.e., not go into the else block). In this sense, it is indeed like separating conditions with AND logic.

You can implement OR logic, not by using commas, but by using a Boolean condition:

guard     true || false    // this guard statement evaluates to true else     {     print("no, not all values in the guard were true")     return     }  print("yes, all of the values in the guard were true")  // this is printed 

or a combination of OR and AND logic, by using a combination of Boolean conditions and optional bindings:

let testString: String? = nil  guard     true || false,     let x = testString,    // this guard statement evaluates to false     true else     {     print("no, not all values in the guard were true")  // this is printed     return     }  print("yes, all of the values in the guard were true") 

This summary from Apple, written about optional bindings in if statements is equally applicable to guard statements:

You can include as many optional bindings and Boolean conditions in a single if statement as you need to, separated by commas. If any of the values in the optional bindings are nil or any Boolean condition evaluates to false, the whole if statement’s condition is considered to be false. The following if statements are equivalent:

if let firstNumber = Int("4"), let secondNumber = Int("42"),     firstNumber < secondNumber && secondNumber < 100     {     print("\(firstNumber) < \(secondNumber) < 100")     } // Prints "4 < 42 < 100"  if let firstNumber = Int("4")     {     if let secondNumber = Int("42")         {         if firstNumber < secondNumber && secondNumber < 100             {             print("\(firstNumber) < \(secondNumber) < 100")             }         }     } // Prints "4 < 42 < 100" 
like image 22
Gene Loparco Avatar answered Sep 16 '22 16:09

Gene Loparco