if let vs guard let
If your coding journey started anything like mine, you had no idea what if let or guard let was! After reading through resources and putting both into practice I still didn't really understand the difference. So, I’m here to make that more clear for the people who can relate.
First off, what is if let or guard let?
if let and guard let are simply Swift’s way of unwrapping (revealing the value of a variable or constant which can contain nil) optional values. Optionals are a binary that Swift uses to say a variable or a constant can either contain a value or be nil (the absence of a value).
Think of optionals as Christmas gifts from the prankster of the family.
Think of optionals as Christmas gifts from the prankster of the family. Looking at the gift you have no idea whats inside. Based on prior experience you know there may be something inside the box, but it also may be empty. You know both outcomes are equally possible but you just have to know what is inside. You take the plunge, tear open the wrapping paper, rip off the lid of the box and find… NOTHING. In this real life scenario you may be hit with disappointment or maybe even relief, no biggie. However, in Swift code this will cause your entire application to Crash!
Swift is a type safe language meaning, it doesn't want this to happen to you. This is why Swift has provided us with if let and guard let, to keep you and your application safe. In short these are tools to help you safely unwrap optional values and use those values in your application.
Lets take a look at if let first and see what it looks like in code:
var name: String?name = "Goku"if let zFighter = name { print("\(name) is the strongest Z fighter!")}// the code above will print out "Goku is the strongest Z fighter!"
The code above shows a scenario where an optional actually has a value. When an optional has a value the code in the brackets will be run. Keep in mind I said: the code inside the brackets will run. We’ll come back to this point later on.
Let us look at a case where we do not assign the string “Goku” to the variable name.
var name: String?if let zFighter = name { print("\(name) is the strongest Z fighter!")}// the code above will not run at all .
In this case, the code wont run at all. This can be confusing when running your code in a real life scenario because you have no indicator that the code didn't run. A better way to show this is to implement an else scenario, for the case when a value contains nil.
var name: String?if let zFighter = name { print("\(name) is the strongest Z fighter!")} else {print("name is nil!")}// the code above will print "name is nil"
Now, remember how I emphasized the fact that code will execute INSIDE the brackets when unwrapping an optional contains a value. This is an important if let feature to remember. the constant that is used in the if statement only exists inside the brackets. outside the brackets it’s a non-factor and the Swift compiler will not know what you’re talking about if you try to use it.
var name: String?name = "Gohan"if let zFighter = name { print("\(name) is the strongest Z fighter!")} else {print("name is nil!")}print("\(name) isn't being treated right in Dragon Ball Super")// the 3rd print statement will trigger an error.
NEXT UP guard let
guard let is very similar to if let except that this function is to be used within a function. guard let unwraps optionals that contain a value, if the optional does not contain a value then the guard statement requires you to abort mission and exit out of the function.
The if guard statement acts as a protector. Nil is the enemy of if guard statements. If nil is detected, it retreats (aka gets out of dodge or in this case out of the function). Unlike the if let statement, if the unwrapped optional contains a value you’re free to use throughout the rest of your function.
var isVillian: Bool?isVillain = truefunc heroOrVillian(name: String) { guard let notVillian = isVillian else { return } if notVillian { print("\(name) is a super hero") } else { print("\(name) is a super villian") }heroOrVillian(name: "spiderman")
In Summary
if let and guard let are tools provided to us to safely unwrap optionals without crashing our entire application.
optionals unwrapped using if let only exist within the curly brackets after the if let statement.
guard lets are used inside functions and require you to exit the function if the unwrapped value returns nil.