Localizable string interpolation doesn't work as expected

216 views Asked by At

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!

3

There are 3 answers

1
Lou Franco On

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

0
Alexnnd On

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 %@";
0
JUsltop On

How many Localizable.strings file you have?

try declare

"hello-name %@" = "Hello, my name is %@"; 

in all your language files.