guard let and if let — Swift Newbies

Ankur Raina
2 min readOct 1, 2021

--

In Swift, a guard statement is similar to if statement except that it is used to transfer the program control out of scope if the condition(s) are not met.

guard condition else {
statements
}

In the else clause, you would generally make a call to return but you can also use some other statements.

With let keyword, both guard and if allow for Optional Binding. (switch also allows it)

Optional Binding allows us to check if an Optional contains a value, and if it does, it allows us to make that value available in a variable.

Let’s consider a dictionary in Swift. In a dictionary, you can get the values by searching through a key. The key may or may not exist in the dictionary, so, it returns an Optional, and we use Optional Binding to store the returned value.

if let

guard let

Notice that guard let has a return in its else clause, so, if there is no value, it will return the scope to the caller.

Also, notice that the value is accessible even after the guard statement inside the scope of the function.

What if guard let isn’t inside a function?

It will result in an error: ‘guard’ body must not fall through, consider using a ‘return’ or ‘throw’ to exit the scope

You can’t use return outside a function but you still have the option of using throw.

However, when you throw an error, you’ll also need to catch and handle it which you cannot do outside a function block. So, it doesn’t make a lot of sense unless you want to terminate the application.

We have declared a custom error and threw it when guard condition didn’t meet.

Cheers!

--

--