UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Why does Swift make us unwrap optionals?

Paul Hudson    @twostraws   

Updated for Xcode 15

Swift’s optionals can either store a value, such as 5 or “Hello”, or they might be nothing at all. As you might imagine, trying to add two numbers together is only possible if the numbers are actually there, which is why Swift won’t let us try to use the values of optionals unless we unwrap them – unless we look inside the optional, check there’s actually a value there, then take the value out for us.

There are several ways of doing this in Swift, but one of the most common is if let, like this:

func getUsername() -> String? {
    "Taylor"
}

if let username = getUsername() {
    print("Username is \(username)")
} else {
    print("No username")
}

The getUsername() function returns an optional string, which means it could be a string or it could be nil. I’ve made it always return a value here to make it easier to understand, but that doesn’t change what Swift thinks – it’s still an optional string.

That single if let line combines lots of functionality:

  1. It calls the getUsername() function.
  2. It receives the optional string back from there.
  3. It looks inside the optional string to see whether it has a value.
  4. As it does have a value (it’s “Taylor”), that value will be taken out of the optional and placed into a new username constant.
  5. The condition is then considered true, and it will print “Username is Taylor”.

So, if let is a fantastically concise way of working with optionals, taking care of checking and extracting values all at once.

In fact, it’s so concise it even gives us a little shortcut. Rather than writing this:

if let number = number {
    print(square(number: number))
}

We can actually write this:

if let number {
    print(square(number: number))
}

It does exactly the same thing – it creates a shadowed copy of number that is unwrapped only inside that condition’s body, just with a bit less repetition.

The single most important feature of optionals is that Swift won’t let us use them without unwrapping them first. This provides a huge amount of protection for all our apps, because it puts a stop to uncertainty: when you’re handing a string you know it’s a valid string, when you call a function that returns an integer, you know it’s immediately safe to use. And when you do have optionals in your code, Swift will always make sure you handle them correctly – that you check and unwrap them, rather than just mixing unsafe values with known safe data.

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.8/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.