|< Why does Swift need both implicitly unwrapped optionals and regular optionals?||Why is optional chaining so important? >|
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() ?? ""
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
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.
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!
Link copied to your pasteboard.