SwiftUI with Localization from the start

Andrew Ho
2 min readNov 23, 2020

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

  • Make sure “Use Base Internationalization” is checked.
  • Add 1 additional locale in addition to your development language, e.g. Chinese, Traditional (zh-Hant)

Step 2: Add Localizable.strings to your project

Don’t worry about stringsDict yet. stringsDict are for more advanced localization problems such as plurals.

Create a “Localizable.strings” file, if you have not done so yet: by clicking File > New > File > Strings File (part of the Resources category). Name it “Localizable.strings”.

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()

— to make localization testing easier. ContentView() is located in your main app file. For example:

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

After following these 3 steps, Text(“Hello”) in ContentView.swift will show the Chinese version, 你好, when locale is set to zh-Hant. Change the locale back to “en” to switch back to English.

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

--

--