< Why does Swift need both implicitly unwrapped optionals and regular optionals? | Why is optional chaining so important? > |
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.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.