I'm currently exploring the different options Swift provides for handling string localization. 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.
If I know in advance that a string will be displayed in the UI and might need to be translated, which of these options is the most appropriate and future-proof for localization?
Which approach is generally considered best practice for strings intended to be shown and translated?
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