iOS. Pluralization. Stringdict with format that contains 2 int arguments

后端 未结 1 1988
刺人心
刺人心 2021-01-20 14:58

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 i

相关标签:
1条回答
  • 2021-01-20 15:38

    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”.

    0 讨论(0)
提交回复
热议问题