How to add regular string placeholders to a transl

2019-02-26 14:04发布

I want to translate this string using a plurar stringdict in swift for iOS

  • stays at %1$@
  • stay at %1$@

Using a simple plural without placeholders works, thanks to this question But when I add a string placeholder I get a crash when accessing it.

The regular plurals are working using the following xml:

<dict>
<key>NSStringLocalizedFormatKey</key>
<string>%#@format@</string>
<key>format</key>
<dict>
    <key>NSStringFormatSpecTypeKey</key>
    <string>NSStringPluralRuleType</string>
    <key>NSStringFormatValueTypeKey</key>
    <string>li</string>
    <key>one</key>
    <string>Sleeps at your place</string>
    <key>other</key>
    <string>Sleep at your place</string>
</dict>
</dict>

And using this swift code to reference the plural above without string placeholder:

 let format = NSLocalizedString("key_to_plural_above", comment: "")
 let label = String.localizedStringWithFormat(format, kidsIds.count)

The problem is when I add a string placeholder to the translation I get a crash when I try to read it. The xml below is generated by a translation tool (lokalise) so I assume it's correct.

<dict>
<key>NSStringLocalizedFormatKey</key>
<string>%#@format@</string>
<key>format</key>
<dict>
    <key>NSStringFormatSpecTypeKey</key>
    <string>NSStringPluralRuleType</string>
    <key>NSStringFormatValueTypeKey</key>
    <string>li</string>
    <key>one</key>
    <string>Sleeps at %1$@</string>
    <key>other</key>
    <string>Sleep at %1$@</string>
</dict>

Using this swift code to get the plural above, I get an unknown crash without any stacktrace:

let format = NSLocalizedString("key_to_plural_above", comment: "")
let label = String.localizedStringWithFormat(format, kidsIds.count, "Name")

1条回答
爷、活的狠高调
2楼-- · 2019-02-26 14:47

Positional parameters n$ are one-based, so in

let label = String.localizedStringWithFormat(format, kidsIds.count, "Name")

"Name" is the second parameter, and you reference it with %2$@:

<key>NSStringLocalizedFormatKey</key>
<string>%#@format@</string>
<key>format</key>
<dict>
    <key>NSStringFormatSpecTypeKey</key>
    <string>NSStringPluralRuleType</string>
    <key>NSStringFormatValueTypeKey</key>
    <string>li</string>
    <key>one</key>
    <string>Sleeps at %2$@</string>
    <key>other</key>
    <string>Sleep at %2$@</string>
</dict>

In your code, %1$@ refers to the first argument kidsIds.count. That is not a string which leads to the crash.

Alternatively, put it into the NSStringLocalizedFormatKey:

<key>NSStringLocalizedFormatKey</key>
<string>%#@format@ at %@</string>
<key>format</key>
<dict>
    <key>NSStringFormatSpecTypeKey</key>
    <string>NSStringPluralRuleType</string>
    <key>NSStringFormatValueTypeKey</key>
    <string>li</string>
    <key>one</key>
    <string>Sleeps</string>
    <key>other</key>
    <string>Sleep</string>
</dict>
查看更多
登录 后发表回答