Swift 5.7's new optional unwrapping syntax

  

Swift 5.7 introduces a new, more concise way to unwrap optional values using if let and guard let statements. Before, we always had to explicitly name each unwrapped value, for example like this:

class AnimationController {
var animation: Animation?

func update() {
if let animation = animation {
// Perform updates
...
}
}
}
But now, we can simply drop the assignment after our if let statement, and the Swift compiler will automatically unwrap our optional into a concrete value with the exact same name:
class AnimationController {
var animation: Animation?

func update() {
if let animation {
// Perform updates
...
}
}
}
Neat! The above new syntax also works with guard statements:
class AnimationController {
var animation: Animation?

func update() {
guard let animation else {
return
}

// Perform updates
...
}
}
It can also be used to unwrap multiple optionals all at once:
struct Message {
var title: String?
var body: String?
var recipient: String?

var isSendable: Bool {
guard let title, let body, let recipient else {
return false
}

return ![title, body, recipient].contains(where: \.isEmpty)
}
}
A small, but very welcome feature. Of course, we still have the option to explicitly name each unwrapped optional if we wish to do so - either for code style reasons, or if we want to give a certain optional a different name when unwrapped.


via: https://www.swiftbysundell.com/articles/swifts-new-shorthand-optional-unwrapping-syntax


Share on Facebook  Share on Facebook


Comments
My Test App

Click To See More Photos

Mobile Apps


More Blogs

Other Headlines


Receive News Updates
  
  Daily Vibe Breaking News
 

Become A Fan
RSS Logo Facebook Logo Twitter Logo Youtube Logo


Sponsors
Download the BV mobile app

Best VPN Service