Swift 5.7 | What’s new in optional binding?

The Blue Prototype
3 min readJun 16, 2022
Photo by Thomas Tastet on Unsplash

Apple made a small change in the syntax of optional binding in the recent version of Swift 5.7 ! Let’s have an introduction about Optional type first.

Optional

An Optional type that represents either a wrapped value or nil, the absence of a value. The types of shortForm and longForm in the following code sample are the same:

let shortForm: Int? = Int("42")
let longForm: Optional<Int> = Int("42")

The Optional type is an enumeration with two cases. Optional.none is equivalent to the nil literal. Optional.some(Wrapped) stores a wrapped value. For example:

let number: Int? = Optional.some(42)
let noNumber: Int? = Optional.none
print(noNumber == nil)
// Prints "true"

You must unwrap the value of an Optional instance before you can use it in many contexts. Because Swift provides several ways to safely unwrap optional values, you can choose the one that helps you write clear, concise code.

Optional Binding

Optional binding is used to conditionally bind the wrapped value of an Optionalinstance to a new variable. For example — In the below code, name is the optional instance variable and it is binded by the new variable to get the unwrapped value via a if let statement.

--

--

Responses (3)