— Swift, Optional Binding, SE-0345, Syntax — 1 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!
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.
Suppose we have an optional variable temperature representing the current temperature:
1var temperature: Double? = 23.5Instead 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.
if (or each case of a switch) must be a single expression. You cannot include complex multi-line code blocks.guard let shorthand for upgrading self from a weak to strong reference.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! 😊