if let: How not to use it

⋅ 1 min read ⋅ Swift Semantic

Table of Contents

Today I want to show you how you should write a code in a way that shows your true intention. I use my old code that misuse if let as an example.

When I wrote this, only God and I understood what I was doing.
Now, only God knows.

You can easily support sarunw.com by checking out this sponsor.

Sponsor sarunw.com and reach thousands of iOS developers.

Problem

I got an optional object with an optional property.

struct User {
let name: String
let address: Address?
}

let user: User? = User(name: "John", address: nil)

There is a time when I need to check for the presence of an object property to treat it differently.

Without much thought, sometimes, my muscle memory will write something like this.

if let user = user, let address = user.address {
// Some logic that use `user`, but not `address`
}

I'm in a hurry, so I ignore the Xcode warning. Many months passed by coming back to refactor my code, and I see this warning.

Value never used warning
Immutable value 'address' was never used; consider replacing with '_' or removing it. Replace 'address' with '_'

I follow the solution and remove it.

if let user = user {
// Some logic that use `user`, but not `address`
}

A few minutes later, my CI failed. My UI tests failing, and I spent minutes fixing them.

What my past self should do

Instead of abusive use of let address = user.address, I should write in a way that expresses the real intent.

... to check for the presence of an object property ...

I should write it like this.

if let user = user, user.address != nil {
// Some logic that use `user`, but not `address`
}

You can easily support sarunw.com by checking out this sponsor.

Sponsor sarunw.com and reach thousands of iOS developers.

Conclusion

By using language features correctly, you do colleagues and your future self a favor. A little bit of thought at a very early stage can save you significant time in the future.


Read more article about Swift, Semantic, or see all available topic

Enjoy the read?

If you enjoy this article, you can subscribe to the weekly newsletter.
Every Friday, you'll get a quick recap of all articles and tips posted on this site. No strings attached. Unsubscribe anytime.

Feel free to follow me on Twitter and ask your questions related to this post. Thanks for reading and see you next time.

If you enjoy my writing, please check out my Patreon https://www.patreon.com/sarunw and become my supporter. Sharing the article is also greatly appreciated.

Become a patron Buy me a coffee Tweet Share
Previous
Dark color

Things you should know about color when adopting dark mode.

Next
Github Actions for iOS projects

How to setup ci for iOS projects with Github Actions.

← Home