Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSLocalizedString With Dynamic Variable (Swift) - Not Working

I began integrating localization into my app using this guide. It worked great until I localized a string that included a dynamic variable. The original was this:

let myString = "I have \(countOfMoney) dollars in my wallet."

Then I tried to mimiic this stack answer to localize it. However, I'm getting an EXC_Bad_Access error. Below is how I tried to localize it.

This is in my Localizable.strings English file:

localizedMsg="I have %@ dollars in my wallet.";

This is in my View Controller:

let countOfMoney = moneyInWallet.count
let localizedMsg = String(format: NSLocalizedString("localizedMsg", comment: ""), countOfMoney)

However, this line shows up as an error when I run the app on the simulator. How do I fix it?

like image 916
Dave G Avatar asked May 16 '16 23:05

Dave G


1 Answers

Your setup isn't correct. Your code should look like this:

let localizedMsg = String(format: NSLocalizedString("I have %d dollars in my wallet.", comment: ""), countOfMoney)

Now run genstrings to get your updated Localizable.strings file.

That will add the line:

"I have %d dollars in my wallet." = "I have %d dollars in my wallet.";

Also note the change from %@ to %d. This assumes that countOfMoney is an integer type. Only use %@ for object pointers.

like image 142
rmaddy Avatar answered Nov 02 '22 14:11

rmaddy