Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: How to localize strings with multiple interpolated parameters?

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?

like image 465
Chris Avatar asked Jun 11 '14 10:06

Chris


1 Answers

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"

like image 148
Jose Servet Avatar answered Oct 11 '22 14:10

Jose Servet