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.

https://developer.apple.com/documentation/swiftui/localizedstringkey


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

Text("Username")

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) {
    Text("Chocolate").tag(Flavor.chocolate)
    Text("Vanilla").tag(Flavor.vanilla)
    Text("Strawberry").tag(Flavor.strawberry)
}

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.

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

Hope this tips will help you enjoy SwiftUI more.