I'm currently reading about the possibilities, which Swift offers for translating Strings. I would like to choose the right option. Meanwhile I'm more confused, instead of becoming more sure. There are LocalizedStringKey, LocalizedStringResource and String with arguments.
Which one should I use, when I know in advance, that the String will become shown on the UI and perhaps translated?
Respectively which option is optimal for translation?
When dealing with localized strings in Swift, especially for UI elements, choosing the right approach is crucial. Here’s a breakdown of the options:
LocalizedStringKey
(Best for SwiftUI)Use when: You are directly using a string in a SwiftUI view (e.g., Text("hello_world")
).
Why? SwiftUI automatically localizes LocalizedStringKey
, making it the best choice for UI text.
Example:
Text("hello_world") // Automatically looks for "hello_world" in Localizable.strings
Pros:
✅ No need to manually use NSLocalizedString
✅ Cleaner SwiftUI code
✅ Supports string interpolation
Cons:
❌ Can’t be used outside SwiftUI (e.g., in business logic)
LocalizedStringResource
(Best for Performance)Use when: You need efficient string translation with better memory handling.
Introduced in: iOS 16
Why? It is more optimized than LocalizedStringKey
, but still works well with SwiftUI.
Example:
Text(LocalizedStringResource("hello_world"))
Pros:
✅ More optimized for localization
✅ Reduces memory overhead
Cons:
❌ Requires iOS 16+
String
with NSLocalizedString
(Best for Non-SwiftUI Code)Use when: You are not using SwiftUI, but need translations in ViewModels, controllers, or business logic.
Why? NSLocalizedString
fetches translations from Localizable.strings
.
Example:
let greeting = NSLocalizedString("hello_world", comment: "Greeting message") print(greeting)
Pros:
✅ Works anywhere (UIKit, business logic, networking)
✅ Supports dynamic strings
Cons:
❌ Not automatically localized in SwiftUI
❌ More verbose