Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting Localized Strings with Multiple Values

I've created a localized string that takes the form similar to

"text_key" = "Collected %d out of %d";

and am using the following formatter:

let numberOfItems = 2
let totalNumberOfItems = 10
let format = NSLocalizedString("text_key", comment: "Says how many items (1st var) were collected out of total possible (2nd var)")
let text = String.localizedStringWithFormat(format, numberOfItems, totalNumberOfItems)

Which gives

"Collected 2 out of 10"

However I can imagine that in some languages it would be more natural to have these values appear in a different order resulting in a non-sensical string such as

"Out of a possible 2 items you collected 10"

I cannot find a simple way to encode this using the standard Swift library such as

"text_key" = "Out of a possible {2%d} items you collected {1%d}"

and can see this getting cumbersome hardcoding these as more values are added.

like image 344
Ben Avatar asked Jul 16 '18 19:07

Ben


1 Answers

String.localizedStringWithFormat() works with “positional arguments” %n$. In your case

"text_key" = "Out of a possible %2$d items you collected %1$d";

would do the trick.

These are documented in fprintf:

Conversions can be applied to the nth argument after the format in the argument list, rather than to the next unused argument. In this case, the conversion specifier character % (see below) is replaced by the sequence "%n$", where n is a decimal integer in the range [1,{NL_ARGMAX}], giving the position of the argument in the argument list.

like image 68
Martin R Avatar answered Oct 15 '22 14:10

Martin R