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

When should you use nil coalescing in Swift?

Paul Hudson    @twostraws   

Updated for Xcode 15

Nil coalescing lets us attempt to unwrap an optional, but provide a default value if the optional contains nil. This is extraordinarily useful in Swift, because although optionals are a great feature it’s usually better to have a non-optional – to have a real string rather than a “might be a string, might be nil” – and nil coalescing is a great way to get that.

For example, if you were working on a chat app and wanted to load whatever message draft the user had saved, you might write code like this:

let savedData = loadSavedMessage() ?? ""

So, if loadSavedMessage() returns an optional with a string inside, it will be unwrapped and placed into savedData. But if the optional is nil then Swift will set savedData to be an empty string. Either way, savedData will end up being a String and not a String?.

You can chain nil coalescing if you want to, although I don’t think it’s common. So, this kind of code is valid if you wanted it:

let savedData = first() ?? second() ?? ""

That will attempt to run first(), and if that returns nil attempt to run second(), and if that returns nil then it will use an empty string.

Remember, reading a dictionary key will always return an optional, so you might want to use nil coalescing here to ensure you get back a non-optional:

let scores = ["Picard": 800, "Data": 7000, "Troi": 900]
let crusherScore = scores["Crusher"] ?? 0

This is definitely a matter of taste, but dictionaries offer a slightly different approach that lets us specify the default value for when the key isn’t found:

let crusherScore = scores["Crusher", default: 0]

You can choose whichever you prefer – when reading dictionary values there’s no real difference.

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.9/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.