Home > Blockchain >  Localizable string interpolation doesn't work as expected
Localizable string interpolation doesn't work as expected

Time:11-08

I'm currently trying to understand why this little piece of code doesn't work as expected:

// ContentView.swift (before var body: some View)
let name = "Emma"

// ContentView.swift (inside var body: some View)
Text("hello-name \(name)")

// Localizable.strings
"hello-name %@" = "Hello, my name is %@";

I have also tried using NSLocalizedString as sometimes it does the trick:

// ContentView.swift (inside var body: some View)
Text(String(format: NSLocalizedString("hello-name %@", comment: "Name"), name))
Text(String(format: NSLocalizedString("hello-name %@", comment: "Name"), name as String))
Text(String(format: NSLocalizedString("hello-name %@", comment: "Name"), name as CVarArg))

But still I don't get Hello, my name is Emma. Do you know why? Thanks!

CodePudding user response:

Use "hello-name" as the key in the strings file and the first arg to NSLocalizedString

CodePudding user response:

I finally found where was the problem! As I'm so dumb, I was filling in the wrong Localizable.strings file.

My app was launching in French (my first iOS language) while I was filling in the English file...

So, the code below is working very fine:

// ContentView.swift (before var body: some View)
let name = "Emma"

// ContentView.swift (inside var body: some View)
// They all work nicely!
Text("hello-name \(name)")
Text(String(format: NSLocalizedString("hello-name %@", comment: ""), name))
Text(String(format: NSLocalizedString("hello-name %@", comment: ""), name as CVarArg))

// Localizable.strings (with the good one this time)
"hello-name %@" = "Hello, my name is %@";
  • Related