Ghostboard pixel

if let shorthand syntax in Swift

Using optional binding is very common in Swift. With the "if let" shorthand syntax it is easier to write and read. It has been introduced with Swift 5.7 and Xcode 14.

if let shorthand syntax in Swift
Photo by Fotis Fotopoulos / Unsplash

if let for optional binding

Optional binding is used to access optional in a safe way. For example, take a look at the following example:

var a: Int? = 5

if let a = a {
    print(a)
}

Here a is an optional and gets shadowed inside the if let code block. In that block, a is no longer an optional. If a is nil, the code block wouldn’t be executed.

However, it is a little bit strange to write and read.

if let shorthand syntax

With the if let shorthand syntax, it becomes easier:

var a: Int? = 5

if let a {
    print(a)
}

It’s not only more clear, but it’s also less error-prone: It’s common practice to use the same variable for the shadowing variable. However, if the name of the variable is long and difficult, a typo can easily happen. Then, you have two similar named variables accessible inside the code block. With the if let shorthand syntax, this cannot happen.

guard

Not only if let is often used for handling optionals, but guard as well. Here you have a similar shorthand syntax:

func doSomething(a:Int?) {
     guard let a else {
          return
     }

     print(a)
}

If you want to learn more about optionals, take a look at my blog post about optionals.

References

if let shorthand for shadowing an existing optional variable

Do you want to learn more about iOS development?

Take a look at the following book (affiliate link):