iosxcodeinternationalization

How to Automatically Add Strings to the Xcode String Catalog?


When I use Text("Lorem") in SwiftUI, it adds a Lorem key to the Xcode String Catalog (Localizable.xcstrings) at build time. I want to achieve the same behavior for strings that are defined outside of views.

Here’s what I’ve tried:

Both approaches work, but only if I manually add the keys to the String Catalog. This is not ideal because if I forget to add a key, it might go unnoticed.

An alternative could be to use Text() throughout my code and pass it around, but I’d prefer to avoid coupling my presentation layer with the rest of my app. I want to pass a String (or a similar type) to my SwiftUI views and then render it using Text(). This way, I can ensure that no modifiers or unintended changes are applied before the string reaches the UI.

What is the best practice for ensuring that strings used throughout the app are automatically added to the String Catalog at build time without relying on Text() for string management?

I'm targeting iOS 15+.


Solution

  • Based on the fact that Text("...") generates a localisation key but LocalizedStringKey("...") doesn't, it seems like the build setting "Localized String SwiftUI Support" is turned on, but "Use Compiler to Extract Swift Strings" is not turned on.

    You should turn on the latter too:

    enter image description here

    In addition to the forms you suggested, you can also do:

    let someText: LocalizedStringKey = "..."
    

    which I think is more idiomatic than LocalizedStringKey("...")

    Other types such as LocalizedStringResource also works with this.