Quick guide to SwiftUI localization

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

Natascha Fadeeva
2 min readNov 7, 2021

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.

"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"))    }}

Originally published at https://tanaschita.com.

--

--