12

How do I use NSLocalizedString to build a string with multiple parameters while giving the translator control to change the order if they wish?

An example in my Localizable.string is:

"score_out_of"="Your score is %i out of %i";

And would be invoked like

[NSString stringWithFormat:NSLocalizedString(@"score_out_of", nil), correct, total];

But on some locales the grammar rules might dictate that total goes before correct. In Objective C it seems the interpolation order is hard coded.

In other languages this is accomplished by naming the parameters, for example in ruby it would be defined like:

out_of: "Your score is %{correct} out of %{total}"

And invoked like:

I18n('out_of', {total: total, correct: correct})

What is the recommended way to accomplish the same thing on iOS / Objective C?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Chris
  • 6,076
  • 11
  • 48
  • 62

1 Answers1

14

According to the documentation

https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265-SW2

Note that you can also use the “n$” positional specifiers such as %1$@ %2$s

So you can simply create your string as

"score_out_of"="Your score is %1$i out of %2$i"

And in other language, it could be

"score_out_of"="Out of %2$i, your score is %1$i"

Axel Guilmin
  • 11,454
  • 9
  • 54
  • 64
Jose Servet
  • 469
  • 4
  • 7