Logo for tanaschita.com

Quick guide to SwiftUI localization

Learn how to support multiple languages in your SwiftUI iOS app.

14 Oct 2021 · 3 min read

Supporting multiple languages is a common task when developing iOS applications. Xcode and SwiftUI make it easy for us to implement localization.

Adding localization to the SwiftUI project

To add localization to a SwiftUI project, perform the following steps:

  1. Create a new empty file called Localizable.strings in the project.
  2. Select the Localizable.strings file and open the Xcode inspector (keyboard shortcut ⌥⌘1).
  3. Tap the Localize button in the Xcode inspector.
  4. Select the project in the Xcode navigator (keyboard shortcut ⌘1)
  5. Add more languages in the Info tab by tapping the + button in the Localization section.

Using localized values in a SwiftUI view

For each localized language, we can now add keys and their translations in the Localizable.strings file.

"hello.world" = "Hello world!";

To use the localized values in a SwiftUI view, the framework provides the LocalizedStringKey type.

Text(LocalizedStringKey("hello.world"))

In the example above, we pass the LocalizedStringKey "hello.world" into the Text view that is used to look up the key in the localization files.

Other SwiftUI views like Label or Picker also accept the LocalizedStringKey type as parameter.

Passing arguments into localized strings

Sometimes, we want to inject dynamic data into our localized strings. We can do this by defining string format specifiers in our localized strings.

"hello %@" = "Hello %@!";

For example, we can use %@ for String types, %d for Int types or %f for Double types.

We can then use String interpolation to inject a parameter.

let name = "Aria"
Text(LocalizedStringKey("hello \(name)"))

Localizing plurals in SwiftUI

To localize plurals we use a Localizable.strigsdict file which is able to interpret the arguments we pass in and select the right localized string based on it. Check out this step-by-step guide on plurals localization in iOS to learn more about it.

Changing the language of the SwiftUI preview

To change the language of a SwiftUI preview, we can set the locale value with the environment modifier.

struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.environment(\.locale, .init(identifier: "de"))
}
}
Image of books
Further reading: SwiftUI by Example
For further reading, check out the SwiftUI by Example book by Paul Hudson. It guides you through dozens of common coding problems with hands-on solutions.

Newsletter

Receive a monthly newsletter about the latest articles and tips.

Image of a reading marmot

Related tags

Written by

Articles with related topics

Latest articles and tips