Check for nil with guard instead of if?

Like some people already answered, you can use let

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

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

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

You can also do a regular boolean check instead of using let

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

A more general case for a boolean check on a guard

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

If you want to be able to modify 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 a boolean check by using commas between the statements.

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

Swift 2.x

You can combine var/let with the boolean check by using where where

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)