if let Shorthand for Optional Binding in Swift 5.7

Arman
1 min readJul 25, 2022

Swift has Optional types representing either a wrapped value or nil, the absence of value. We can make a variable optional with a question mark ?:

let foo: String?

To get the optional’s value, it needs to be unwrapped. One of the ways of unwrapping optionals is optional binding which creates an unwrapped variable that shadows the existing optional variable:

let foo: String? = "something optional"

if let foo == foo {
...
}

In the example above, we used the same name for the constant as we used for the optional. Therefore we repeated the referenced identifier twice, which can cause these optional binding conditions to be redundant and hard to read, especially when using lengthy variable names:

let someRandomVariableName: String? = ...
let anotherRandomVariableName: String? = ...

if let someRandomVariableName= someRandomVariableName, let anotherRandomVariableName= anotherRandomVariableName{
...
}

⭐ In Swift 5.7, we now have a shorthand that let us simplify the code:

if let foo {
...
}

And in the case of the lengthy variable names:

if let someRandomVariableName, let anotherRandomVariableName{
...
}

It can also be used with guard letstatements:

guard let foo else {
...
}

This new shorthand can reduce duplication, especially of lengthy variable names, making code easier to write and read.

You can read more about the new if let shorthand in the SE-0345 proposal.

--

--

Arman

Code, conquer, and share. I write about software development and coding challenges. Let's learn and grow together!