These are some notes from moving the count strings in a SwiftUI app ("3 books", "1 session", that kind of thing) off NSString(format:) and onto the typed LocalizedStringResource symbols that Xcode generates from String Catalogs. The app keeps its features in a Swift package with its own .xcstrings catalogs and ships in about twenty locales, and the whole thing started from a small bug where a VoiceOver label read out a raw key instead of its text, because the key was paired with the wrong table.
You already have the generated symbols
The first thing worth knowing is that you don't need to write or check in any generated layer for this. At build time Xcode generates a LocalizedStringResource member for every manually added catalog entry, and it does that for Swift package targets too, not only for the app target. The output lands in the target's DerivedSources as GeneratedStringSymbols_<Table>.swift, one file per catalog, and each member carries its key, its table and its bundle together, so the "wrong table" class of bug goes away once a view takes a resource instead of a key.
There was an older branch in the project that aimed at the same thing by checking in its own generated symbols and a gate that compared them byte for byte, and it had grown huge and stalled. Once it was clear Xcode already does the generation, the branch had nothing left to stand on, so it got closed and the work landed as a small change on top of what Xcode gives you.
Using a symbol for a plural looks like this:
// In a view: the accessor for a %lld plural takes an Int
Text(.Library.libraryEbooksCount(bookCount))
// 1 → "1 book"
// 1234 → "1,234 books" (en), "1.234 Bücher" (de)
// Outside a view (a reducer building a toast), resolve in the process locale
let text = String(localized: .Library.libraryEbooksCount(bookCount))
For an API that wants a String and not a Text, we added a tiny helper that resolves the resource in the view's locale, since String(localized:) on its own uses the process locale and not whatever @Environment(\.locale) says:
extension LocalizedStringResource {
func resolved(in locale: Locale) -> String {
var resource = self
resource.locale = locale
return String(localized: resource)
}
}
A couple of small things came up while moving the call sites over:
-
String(localized:)andText(resource)group the number for the locale, so "1234 books" becomes "1,234 books".NSString(format:)never did that, which makes it a visible change you should mention to whoever reviews it (it's the better output, but it is a change). - The type of the generated accessor follows the placeholder. A
%dplaceholder gives you anInt32parameter and%lldgives youInt, so we moved nine entries from%dto%lldin every locale. A nice side effect is that reverting one of them to%dfails to compile, instead of narrowing silently at every call site. - Two of the catalogs had different JSON key spacing (
"key": {in one,"key" : {in the other), so re-dumping a catalog through a JSON library would have rewritten every line of it. We edited them line by line and JSON-diffed the result to check only the intended keys changed. Also, an edit script that matches nothing exits 0, so assert how many lines it changed.
The one plural category covers more than 1
Some of the catalogs had plural entries whose one form was written with a literal "1", like "1 книга" in Russian. That looks fine until you remember that CLDR plural categories are rules and not numbers. In Russian, Ukrainian, Croatian and Serbian the one category also covers 21, 31, 101 and so on, and in French and Brazilian Portuguese it covers 0. So a header for 21 books read "1 книга", and a French one for zero audiobooks read "1 livre audio".
Every one form should print the count. We fixed 18 of them across those six locales ("1 livre audio" → "%lld livre audio"), and the tests pin the counts that are not 1:
/// Russian, Ukrainian, Croatian and Serbian put 21 in the `one` category.
@Test(arguments: Header.allCases, ["ru", "uk", "hr", "sr"])
func aOneFormPrintsTwentyOne(header: Header, language: String) {
Self.expectOneForm(header, count: 21, language: language)
}
/// French and Brazilian Portuguese put 0 in the `one` category.
@Test(arguments: Header.allCases, ["fr", "pt-BR"])
func aOneFormPrintsZero(header: Header, language: String) {
Self.expectOneForm(header, count: 0, language: language)
}
The helper checks both that the resolved string matches the catalog's one form and that it contains the count, because a literal "1" in the catalog would match the first check and still be wrong for every other number in the category.
A missing key does not fall back to English
There was a VoiceOver label for a row in the statistics screen, a single flat format with %d books, %d sessions in it, which read "1 books". The fix was to turn it into a four-argument frame (%1$@, %2$@ reading time, %3$@, %4$@) and fill the two counts from proper plural entries. I rebuilt that frame in English only, on the assumption that the other locales would fall back to English until the next translation pass, which is what I'd expect from Bundle.localizedString and friends.
A German test showed otherwise. With the German entry gone, the label came out as:
Fantasy2h 30m1.234 Bücher1 Sitzung
The generated symbol for a key-named entry carries its own defaultValue, and for this entry Xcode generated it from the placeholders alone, something like "\(arg1)\(arg2)\(arg3)\(arg4)". When a locale has no entry for the key, that defaultValue is what you get, so the arguments come out run together with no separators and no words between them, and VoiceOver happily reads that out. English is never consulted.
So we put the translations back. The 19 existing translations were rebuilt from their old wording with a small script that only swapped the two %d … fields for %3$@ and %4$@, and a JSON diff confirmed that key was the only one that changed. The test that caught it stays:
@Test
func theLabelResolvesInTheGivenLocale() {
let label = GenreStatRowAccessibility.label(
for: Self.stats(books: 1_234, sessions: 1),
locale: Locale(identifier: "de")
)
#expect(label == "Fantasy, \(formatReadingTime(150)) Lesezeit, 1.234 Bücher, 1 Sitzung")
}
With generated string symbols, ship every format key in every locale, or at least test the locales you care about, because a missing one reads as its arguments glued together.
Top comments (0)