if let

How not to use it

Swift Semantic My past self

I always struggle at writing a short post for my tip section. Most of my article starts as an idea for my tip section, and then it grows into a long one. So today, I come up with a new tag, my past self. I will share an example and mistake I made or see. I think it will fit well into the tip section.

Today I will talk about how not to use if let.

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

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 where I need to check for the presence of an object property so I can treat it differently.

Without much thought, some time, 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 it.

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`

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.

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 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 — entirely for free.

← Home