SwiftUI with Localization from the start

strings vs. stringsDict, 3 steps from initial setup to easy testing during Xcode 12.3 SwiftUI development.

It is best to build app with Internationalization in mind and support localization from the start of the project. Get these first 3 steps working first, before worrying about stringsDict, Xcode Localization Catalog, XLIFF, etc.

Step 1: Add Localizations to your project info page

  • Add 1 additional locale in addition to your development language, e.g. Chinese, Traditional (zh-Hant)

Step 2: Add Localizable.strings to your project

Activate “Localization” in the inspector view of the Localizable.strings file to select and confirm the locale strings files you want to create — one file for each locale.

Select a newly created Localizable.strings locale file, e.g. the “Chinese, Traditional” file and add a row to the end: “Hello” = “你好”;

Step 3: Add locale into environment variable for ContentView()

ContentView().environment(\.locale, .init(identifier: “zh-Hant”))

if your project has other environment variables, these can be stacked like this:

ContentView()

.environment(\.locale, .init(identifier: “zh-Hant”))

.environment(\.managedObjectContext, persistenceController.container.viewContext)

This means you can test the app by changing the locale parameter.

Step 3 has been summarized from Benoit Pasquier’s page. See first reference below.

Conclusion

Note 1: LocalizedStringKey is case-sensitive. If the key used in in the strings file is “hello” = “你好”; translation will not occur for Text(“Hello”).

Note 2: When translation fails due to missing key in locale string file, the original key text is displayed without error message, e.g. “Hello”.

References

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store