swiftswiftuilocalization

How to use dynamic localization keys with SwiftUI


I'm trying to display a localized text based on an ID. I have a lot of these, so it feels more efficient to just add dynamically the ID to the string.

The string file looks like this:

"users.1.name" = "Alice"
"users.2.name" = "Bob"
"users.3.name" = "Charles"
...

If I do the following, hardcoding the ID, it works as expected and displays the associated translated key:

Text("users.1.name")

However if I do this it only displays the string:

Text("users.\(user.id).name")
// displays "users.1.name" instead of "Alice"

I've also tried:

Text(LocalizedStringKey("users.\(user.id).name"))
// displays "users.1.name" instead of "Alice"

Am I missing something or is this not possible?


Solution

  • You need then the following. Tested with Xcode 11.4 / iOS 13.4

    Text(NSLocalizedString("users.\(id).name", comment: ""))