Swift 6.2 makes it easier to interpolate strings with optional values.
What’s The Problem?
In this SwiftUI view I need to create a text string from an optional integer value:
struct CounterView: View {
let count: Int?
var body: some View {
Text("The count is \(count)")
}
}
The compiler warns about the optional value:
String interpolation produces a debug description for an optional value; did you mean to make this explicit?
The compiler suggests either providing a default value or to use String(describing:)
to silence the warning.
Using the nil-coalescing operator to provide a default value removes the warning but is not ideal. The default value has to match the type of the optional value. That can work when dealing with an optional string. In this example I have an optional Int and there may not be a sensible default value for the nil
case. For example, I could use zero:
// The count is 0
Text("The count is \(count ?? 0)")
The alternative of using the String(describing:)
approach is both clumsy and ends up showing the nil
value:
// The count is nil
Text("The count is \(String(describing: count))")
What I want is a way to provide a default string regardless of the type of the optional value.
Default Value Parameter
In Swift 6.2, String interpolation has a new default value parameter that accepts a string regardless of the type of the optional value:
// The count is not set
Text("The count is \(count, default: "not set")")
That’s an improvement over outputting nil
.
Localization
One issue is that I’ve been unable to get this to work with localization. The problem seems to be that LocalizedStringKey
doesn’t support the default value parameter. So this doesn’t work:
// Not Supported
let key = LocalizedStringKey("The count is: \(count, default: "not set")")