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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With