HàPhan 河

SwiftUI's LocalizedStringKey

When doing localization with UIKit, we need to convert the key to expectation string by using NSLocalizedString method. We also need to reload target views when language changed.

self.lblTitle = "Untitled".localized

Things getting easier with SwiftUI. There's new struct was introduced, LocalizedStringKey. We just need to assign correct key to correct label, the rest is on the framework.

Let take a quicklook at official document.


They say, when we use the initializer with a string like Text("Hello World"), SwiftUI will convert to a LocalizedStringKey and uses that to lookup the a localization of the Hello World string.

There're some elements that use string as param for initializer


Button("Sign In", action: signIn)

Label("Lightning", systemImage: "bolt.fill")

Link("View Our Terms of Service",
      destination: URL(string: "https://www.example.com/TOS.html")!)

Picker("Flavor", selection: $selectedFlavor) {

Toggle("Vibrate on Ring", isOn: $vibrateOnRing)

They are called stringLiteral. But how about using variable instead of fixed string?

var signTitle = "Sign In"
Button(signTitle, action: signIn)

This should not work automatically to prevent unexpected values. To use localized string instead of variable's raw data, we just need to convert it to localized key manually.

var signTitle = "Sign In"
Button(LocalizedStringKey(signTitle), action: signIn)

Last but not least, it takes less effort than to UIKit to change language while app is running. A simple line of code to switch Locale, all LocalizedStringKeys, include all child-views, will be reloaded automatically.

    .environment(\.locale, .init(identifier: "ja"))

Hope this tips will help you enjoy SwiftUI more.