6

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?

Community
  • 1
  • 1
Dave G
  • 12,042
  • 7
  • 57
  • 83
  • Does this answer your question? [NSLocalizedString with swift variable](https://stackoverflow.com/questions/26277626/nslocalizedstring-with-swift-variable) – adev Feb 18 '20 at 01:23

1 Answers1

15

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.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • I just mimicked the form of your code and it worked, so thank you. What did you mean by run genstrings though? – Dave G May 17 '16 at 13:51
  • 2
    `genstrings` is the tool that scans all of your source code for calls to `NSLocalizedString` and generates the `Localizable.strings` file for you. – rmaddy May 17 '16 at 15:16