Notice: Undefined index: understanding-swift in /var/sites/ on line 89
When should you use nil coalescing in Swift? - a free tutorial

NEW: Subscribe to Hacking with Swift+ and accelerate your learning! >>

When should you use nil coalescing in Swift?

Paul Hudson    @twostraws   

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.

Hacking with Swift is sponsored by NSSpain

SPONSORED Announcing NSSpain 2020: Remote Edition! An online, continuous conference for iOS developers. We’ll start on Thursday and finish on Friday, with talks, activities, and lots of fun for 36 hours, non-stop. Sound good? Join us!

Find out more

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

Buy Pro Swift 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 (Vapor Edition) 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 Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Link copied to your pasteboard.