问题
My question is similar to How to add regular string placeholders to a translated plurals .stringdict in swift ios but I am trying to understand if it is possible to pass 2 int parameters to strings dict.
Say if I want to translate something like:
1 apple : 3 pears
2 apples : 1 pear
Is it possible to do it in one localized format string like:
let apples = 1
let pears = 3
let applesAndPears = String.localizedStringWithFormat(<format>, apples, pears)
print(applesAndPears)
or do I have to combine them separately?
回答1:
One format is sufficient. You can use multiple placeholders in the NSStringLocalizedFormatKey
entry, and for each placeholder a separate dictionary with the plural rule. Example:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>apples_and_pears</key>
<dict>
<key>NSStringLocalizedFormatKey</key>
<string>%#@num_apples@ : %#@num_pears@</string>
<key>num_apples</key>
<dict>
<key>NSStringFormatSpecTypeKey</key>
<string>NSStringPluralRuleType</string>
<key>NSStringFormatValueTypeKey</key>
<string>ld</string>
<key>zero</key>
<string>no apple</string>
<key>one</key>
<string>1 apple</string>
<key>other</key>
<string>%ld apples</string>
</dict>
<key>num_pears</key>
<dict>
<key>NSStringFormatSpecTypeKey</key>
<string>NSStringPluralRuleType</string>
<key>NSStringFormatValueTypeKey</key>
<string>ld</string>
<key>zero</key>
<string>no pear</string>
<key>one</key>
<string>1 pear</string>
<key>other</key>
<string>%ld pears</string>
</dict>
</dict>
</dict>
</plist>
Usage:
let apples = 1
let pears = 3
let format = NSLocalizedString("apples_and_pears", comment: "")
let applesAndPears = String.localizedStringWithFormat(format, apples, pears)
print(applesAndPears) // 1 apple : 3 pears
This can be combined with positional parameters: if the format is changed to
<key>NSStringLocalizedFormatKey</key>
<string>%2$#@num_pears@ : %1$#@num_apples@</string>
then the output becomes “3 pears : 1 apple”.
来源:https://stackoverflow.com/questions/55752969/ios-pluralization-stringdict-with-format-that-contains-2-int-arguments