Check zero with guard instead if?

Is there an equivalent guard checking if a variable is nil ? If so, how could I translate an instruction like this instead of guard ?

 if post["preview"]! != nil { //do stuff } else { //handle case where the variable is nil } 
+6
source share
4 answers

As some people have already answered, you can use let

 guard let preview = post["preview"] else { /* Handle nil case */ return } 

If you are not using a variable, you can use the underscore to not declare the variable and avoid the warning.

 guard let _ = post["preview"] else { /* Handle nil case */ return } 

You can also do regular boolean check instead of using let

 guard post["preview"] != nil else { /* Handle nil case */ return } 

More general case for boolean checking on a guard

 guard conditionYouExpectToBeTrue else { /* Handle nil case */ return } 

If you want to be able to change the variable, you can use var instead of let

 guard var preview = post["preview"] else { /* Handle nil case */ return } 

Swift 3.0

You can combine var/let with logical validation using commas between statements.

 guard let preview = post["preview"], preview != "No Preview" else { /* Handle nil case */ return } 

Swift 2.x

You can combine var/let with boolean checking using where

 guard let preview = post["preview"] where preview != "No Preview" else { /* Handle nil case */ return } 
+22
source

You can use guard to capture the value from the post dictionary:

 guard let value = post["preview"] else { return // or break, or throw, or fatalError, etc. } // continue using `value` 
+1
source

You can use protective devices with let .

 guard let preview = post["preview"] else { //handle case where the variable is nil } 
+1
source

I think you might need a guard-let construct, for example:

 guard let preview = post["preview"] else { */ nil case */ } /* handle non-nil case here... preview is non-nil */ 
+1
source

All Articles