marcgg
marcgg

Reputation: 66495

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?

Upvotes: 1

Views: 1002

Answers (2)

CodingByJerez
CodingByJerez

Reputation: 241

I'm not a SwiftUI expert but you can use:


let key:String = "users.\(user.id).name"
Text(LocalizedStringKey(key))

// OR compact

Text(LocalizedStringKey(String("users.\(user.id).name")))


Upvotes: 0

Asperi
Asperi

Reputation: 258345

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

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

Upvotes: 1

Related Questions