Understanding localization with LocalizedStringKey in SwiftUI
Learn the advantages and limits of LocalizedStringKey in SwiftUI.
07 Oct 2024 · 5 min read
Working with localized strings in SwiftUI can sometimes be confusing due to the variety of available approaches using LocalizedStringKey or NSLocalizedString. Here are some examples of valid ways to use localized strings in SwiftUI:
Text("hello.world")Text(LocalizedStringKey("hello.world"))Text(NSLocalizedString("hello.world", comment: ""))Text(String(format: NSLocalizedString("hello", comment: ""), name))
Let's dive deeper into these approaches and understand how they work and what their differences are.

SwiftUI's LocalizedStringKey type
LocalizedStringKey is a type that SwiftUI uses to handle localized strings. It interprets keys from the app's .strings or .xcstrings files and replaces them with their localized equivalents at runtime.
When we pass a string literal into a SwiftUI view like Text or Button, SwiftUI automatically converts it into a LocalizedStringKey:
Text("hello.world") // Interpreted as LocalizedStringKey at compile-time
While SwiftUI infers LocalizedStringKey from string literals, we can also explicitly use the type in code:
Text(LocalizedStringKey("hello.world")) // Explicitly using LocalizedStringKey
This can be helpful when passing strings dynamically, as SwiftUI only treats string literals as LocalizedStringKey. For instance, if we pass a string variable to a Text view, SwiftUI will not interpret it as a key, but as plain text.
One significant limitation of LocalizedStringKey in SwiftUI is its inability to handle formatted strings that include dynamic content. For instance, consider the localized key pair:
"hello" = "Hello %@";
In this case, we must revert to using NSLocalizedString, which allows for proper string formatting and parameterization.
Using NSLocalizedString
If we need more control over localization such as runtime flexibility or string formatting, we can use the Foundation API NSLocalizedString. This function retrieves a localized String from the app's localization files.
Text(NSLocalizedString("hello.world", comment: ""))
For strings that require parameters or formatting, NSLocalizedString works well:
Text(String(format: NSLocalizedString("hello", comment: ""), name))
To streamline localization with NSLocalizedString, we can add an extension to the String type:
extension String {var localized: String {return NSLocalizedString(self, comment: "")}func localized(_ args: CVarArg...) -> String {let localizedString = NSLocalizedString(self, comment: "")return String(format: localizedString, arguments: args)}}
With this extension, we can simplify our localized string handling as follows:
Text("hello.world".localized)Text("hello".localized(name))



Newsletter
Like to support my work?
Say hi
Related tags
Articles with related topics
Latest articles and tips



