Providing a default value in a String interpolation
You’re more of a video kind of person? I’ve got you covered! Here’s a video with the same content than this article 🍿
Advertisement
Superwall helps you grow revenue, manage subscriptions, and run price tests faster than anybody.
Stop manually presenting paywalls.
Use Superwall's campaigns and placements to show paywalls at any point, use Stripe for web checkout, and manage metrics like MRR using our charts.
Sponsors like Superwall really help me grow my content creation, so if you have time please make sure to check out their survey: it’s a direct support to my content creation ☺️
Let’s take a look at this code:
We’re using an Optional inside a String interpolation, and so we’re also using the nil-coalescing operator ?? to provide a default value to be used when the Optional will be nil.
This code is perfectly correct, however since Swift 6.2 there’s a newer and more powerful syntax to handle this situation!
In Swift 6.2, we no longer need to use the nil-coalescing operator, because String interpolation has gained support for a default value that will be used when the Optional is nil:
And what’s great is that this new syntax is actually more powerful than using the nil-coalescing operator!
To understand why, let’s have a look at a second example:
This time, if I try to build the code we’ll get a compilation error:
The type of the Optional doesn’t match that of the default value: this is a situation that the nil-coalescing operator doesn’t handle.
However, by using the new syntax the problem is immediately resolved, because the type of the default value no longer needs to match that of the Optional:
That’s all for this article, I hope you’ve enjoyed discovering this new addition of Swift 6.2 😌
Here’s the code if you want to experiment with it!
import Foundation
let age: Int? = nil
print("Your age is: \(age, default: "unknown")")