Localize Interpolated String: Why Only String Value Work?

SwiftUI needs to generate a string with format specifier so that it does work with the current localization mechanisms that exist on Apple's platforms and it does so by leveraging ExpressibleByStringInterpolation.

This is especially important for the interoperability story because you might have an existing localized string file and you want to use it in SwiftUI; but it's also very much important to use the tools that allows you to produce correct localization in multiple languages; for example, by supporting plural rules (via .stringdict) but also different positions in the sentence for the "variable"s. These are features that already exists and work well.

When you're interpolating a numeric value SwiftUI will choose a format specifier appropriate for that type. You have the ability to force a different format specifier:

Text("Guests: \(party.guests.count, specifier: "%d")").

Additionally, SwiftUI also supports formatters directly in the interpolation:

Text("Party Date: \(party.startDate, formatter: partyDateFormatter)").

This will run the localized string look up and then apply the formatter.

5 Likes