使用多个值格式化本地化字符串

Ben*_*Ben 6 localization swift

我创建了一个本地化的字符串,其形式类似于

"text_key" = "Collected %d out of %d";
Run Code Online (Sandbox Code Playgroud)

并且正在使用以下格式化程序:

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)
Run Code Online (Sandbox Code Playgroud)

这使

"Collected 2 out of 10"
Run Code Online (Sandbox Code Playgroud)

但是我可以想象,在某些语言中,让这些值以不同的顺序出现会更自然,从而导致无意义的字符串,例如

"Out of a possible 2 items you collected 10"
Run Code Online (Sandbox Code Playgroud)

我找不到使用标准 Swift 库对其进行编码的简单方法,例如

"text_key" = "Out of a possible {2%d} items you collected {1%d}"
Run Code Online (Sandbox Code Playgroud)

并且可以看到随着更多值的添加,这变得越来越繁琐的硬编码。

Mar*_*n R 6

String.localizedStringWithFormat()与“位置参数”一起使用 %n$。在你的情况下

"text_key" = "Out of a possible %2$d items you collected %1$d"
Run Code Online (Sandbox Code Playgroud)

会做的伎俩。

这些记录在fprintf

转换可以应用于参数列表中格式之后的第 n 个参数,而不是下一个未使用的参数。在这种情况下,转换说明符字符 %(见下文)被序列“%n$”替换,其中 n 是 [1,{NL_ARGMAX}] 范围内的十进制整数,给出参数在参数中的位置列表。

  • @AaronBratcher:仍然对我有用,以“Out of a possible %2$@ items youcollected %1$@”作为格式字符串。 (2认同)