A Shorter Version of if let

Aside from all the new features in SwiftUI in iOS 16, Apple also announced Swift 5.7, which will come along with the release of Xcode 14. Let’s see a minor but welcome change in Swift 5.7.

Swift has the concept of accessories that many programming languages ​​do not have. An optional type means that it can either have a value or there is no value. Swift forces you to check if an accessory has a value before using it.

swift-57-optional binding

Optional binding is a common way to find out if an option has a value or not. Here is an example of a code snippet that uses optional binding:

If you’re new to Swift, this is it if let keyword means that if the optional phone contains a value to which the value is saved myPhone. Inside if block, myPhone is a constant that must contain a value.

To simplify the constant or variable naming, we usually write the code like this:

We make the constant name the same as the optional one.

Optional binding in Swift 5.7

In Swift 5.7, Apple further allows us to simplify the code as below:

This is a minor change in Swift 5.7. However, since optional binding is often used to write Swift code, this should save you a few keystrokes and make the code more readable.

Note: If you are new to Swift, check out our free Swift guide to start learning the Swift programming language.


Protocol-oriented programming in Swift: Is it better than object-oriented programming?


What’s new in Xcode 12 and Swift 5.3


An Introduction to Operator Overload in Swift


Leave a Reply

Your email address will not be published.