Skip to content
DeveloperMemos

Swift 5.7: If Let Shorthand for Unwrapping Optional Variables

Swift, Optional Binding, SE-0345, Syntax1 min read

In Swift, we often use if let or guard let to safely unwrap optional values. However, the syntax can sometimes feel verbose, especially when shadowing an existing optional variable. Swift 5.7(proposal SE-0345) addresses this by introducing a more concise way to handle optional binding. I'm a little bit late writing about it, but let's take a look anyway!

The New Shorthand

Starting from Swift 5.7, you can use the following shorthand syntax for unwrapping optionals:

1if let temperature {
2 // Code that uses the unwrapped `temperature`
3}

This allows you to directly use the unwrapped value without explicitly declaring a new variable. Let's take a closer look at how this works.

Example

Suppose we have an optional variable temperature representing the current temperature:

1var temperature: Double? = 23.5

Instead of the traditional if let:

1if let unwrappedTemperature = temperature {
2 print("The current temperature is \(unwrappedTemperature)°C.")
3}

We can now use the shorthand:

1if let temperature {
2 print("The current temperature is \(temperature)°C.")
3}

The temperature variable is automatically unwrapped and available within the scope of the if block.

Benefits

  • Conciseness: The new shorthand reduces boilerplate code, making your Swift code cleaner and more readable.
  • Swift-like: It aligns with Swift's philosophy of providing expressive and intuitive syntax.

Limitations

  • Each branch of the if (or each case of a switch) must be a single expression. You cannot include complex multi-line code blocks.
  • It doesn't extend to properties inside objects...

Some Related Proposals

  • Swift 4.2 (Xcode 10.0) introduced guard let shorthand for upgrading self from a weak to strong reference.
  • Swift 5.8 (Xcode 14.3) allowed implicit self for weak self captures after self is unwrapped.

Swift 5.7 brings us this handy shorthand for optional unwrapping, making our code more elegant and efficient. If you're using Swift 5.7 or later, give it a try! 😊