Adam Rush

@Adam9Rush

8 June, 2022

Introduction

Along with all the new features provided with the updates during WWDC22, we are also provided with a brand new version of Swift, which is Swift 5.7.

Optional values are a key part of Swift development, annotated with the ? throughout our Swift code.

There is a brand new way to unwrap optional values and the syntax is a neat improvement.

Previous Unwrapping Optional Syntax

Let’s consider we have a basic application with the following struct:

struct BankUser {
    var name: String?
    var balance: Double?
    var transactions: [String]
}

As you can see name and balance are both optional values, which means they could be nil and we have to check this when using the values.

You would typically do this by using a guard statement or if let statement like the following:

struct BankUser {
    var name: String?
    var balance: Double?
    var transactions: [String]
    
    func retrieveUser() {
        if let name = name {
            print("The users name is: \(name)")
        }
        
        guard let name = name else { return }
        print("The users name is: \(name)")
    }
}

Both of these examples will work perfectly fine, and each can be used based on the implementation.

New Unwrapping Optional Syntax

In Swift 5.7 we have a brand new way to unwrap optional values, we no longer have to define the unwrapped value, instead, the compiler will do this for you using the same name as the initial value.

struct BankUser {
    var name: String?
    var balance: Double?
    var transactions: [String]
    
    func retrieveUser() {
        if let name {
            print("The users name is: \(name)")
        }
        
        guard let name else { return }
        print("The users name is: \(name)")
    }
}

It’s a small change but how neat is this 🤩

What Next?

It’s always a great idea to keep an eye on the Swift Evolution, which contains all the proposals that have been accepted and will be coming soon in the Swift language.

Sponsor

Subscribe for curated Swift content for free

- weekly delivered.