iosswiftpluralize

Pluralization with number and name (swift stringsdict)


I have a stringdict and following sentence I want to translate in several languages:

<key>myKey</key>
<dict>
    <key>NSStringLocalizedFormatKey</key>
    <string>My friend %#@name@ has %#@count@.</string>
    <key>count</key>
    <dict>
        <key>NSStringFormatSpecTypeKey</key>
        <string>NSStringPluralRuleType</string>
        <key>one</key>
        <string>one dog</string>
        <key>other</key>
        <string>%d dogs</string>
    </dict>
</dict>

What I want is to use following code, to create my String

let name = "Peter"
let dogs = 3
let myString = String(format: NSLocalizedString("myKey", comment:""), name, dogs)

I have expected to get "My friend Peter has 3 dogs.", but I get an error. So maybe have someone a tip and can help me, how I could use strings in the dict, or maybe there is another way to do it?


Solution

  • In addition to what Andreas said: There is no dictionary for the %#@name@ variable in the format string, but you can simply use %@ for a Swift string instead. The complete stringsdict entry then becomes

    <key>myKey</key>
    <dict>
        <key>NSStringLocalizedFormatKey</key>
        <string>My friend %@ has %#@count@.</string>
        <key>count</key>
        <dict>
            <key>NSStringFormatValueTypeKey</key>
            <string>d</string>
            <key>NSStringFormatSpecTypeKey</key>
            <string>NSStringPluralRuleType</string>
            <key>one</key>
            <string>one dog</string>
            <key>other</key>
            <string>%d dogs</string>
        </dict>
    </dict>