Swift If Let Explained

if let is a awesome tool in Swift

What Does If Let Do

If let is a great way to combine a nil check and an if statement into one line. Let’s say we need check if the variable xCondition is not nil and true.

In other languages, you would do something like this:

let xCondition: Bool? = true
if xCondition != nil, xCondition! {
    print(xCondition!)
    // ... do something
}

In Swift, you can use if let:

let xCondition: Bool? = true
if let xCondition = xCondition, xCondition {
    print(xCondition)
    // ... do something
}

This has the benefit of not needing any force unwraps with the exclamation mark !.

You can also combine variables and have multiple let statements.

let xCondition: Bool? = true
let yCondition: Bool? = true

if let xCondition = xCondition, let yCondition = yCondition, xCondition && yCondition {
    print(xCondition)
    print(yCondition)
}

Why Should You Use If Let

Using if let statements will make your code better by not having to force unwrap variables.

Force unwrapping with an exclamation mark ! is highly frowned upon. This is because it can cause crashes and nil pointer errors. You should try to avoid using force unwraps ! whenever possible.

If let also allows you to get rid of having question marks used for optional chaining. For example this code:

bird.skills?.sing()
bird.skills?.fly()

Can be simplified into something like this:

if let skills = bird.skills {
    skills.sing()
    skills.fly()
}

Using the if let allows us to reason about the code easier from a quick glance. It is obvious from the new code that the block inside the if let will not run if bird.skills is nil.

Why Optionals Are Important

Optionals can be frustrating if you’re a beginner. They can seem unnecessary and just add a bunch of !s and ?s to your code.

However optionals are very important and personally one of my favorite features of Swift. Optionals get rid of a whole class of nil-pointer exception bugs. They force the developer to think about whether a variable can be nil or not.

If you’ve worked in another language, such as Java you’ll know what I’m talking about. Without optionals, crashes will happen often, simply because a variable is nil.

I’ve written an entire article on nil errors here if you’d like to learn more.

Guard Statements - Alternative To If Let

Guard statements serve a similar purpose to if let statements. However, instead of executing a block of code inside curly braces {} if the variable is non-nil, guard statements will return and cease execution of the current block.

Here’s an example of a guard statement:

func test() {
    var str: String?

    guard let unwrappedStr = str else {
        print("str is nil!")
        return
    }
    print(unwrappedStr)
}

test()

The above code will print str is nil!. The second print statement is never reached because of the card statement. Guard statements are great when you want your code execution to end if a certain variable is nil.

If you liked this post and want to learn more, check out The Complete iOS Developer Bootcamp. Speed up your learning curve - hundreds of students have already joined. Thanks for reading!

Eddy Chung

I teach iOS development on ZeroToAppStore.com.

Similar Posts