Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 958
max82 Avatar asked Apr 13 '18 06:04

max82


People also ask

How do I localize a string in Swift?

Select the project and under “Localizations”, click the “+” icon. Add any language you want (I selected Italian) then click on “Finish”. Now go back to Localizable. string file, select it and on the File Inspector (right menu) select “Localize”.

How does NSLocalizedString work?

NSLocalizedString is a Foundation macro that returns a localized version of a string. It has two arguments: key , which uniquely identifies the string to be localized, and comment , a string that is used to provide sufficient context for accurate translation.

What is string localization?

The Localization IdentifierAn unique identifier is attached to each translated string called the "Localization Identifier". It is used to search the dictionaries and locate the value of the string in different languages.


2 Answers

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>
like image 132
Martin R Avatar answered Sep 23 '22 11:09

Martin R


You are missing the format type key:

<key>NSStringFormatValueTypeKey</key>
<string>d</string>

For more details on this, see String Format Specifiers

like image 23
Andreas Oetjen Avatar answered Sep 25 '22 11:09

Andreas Oetjen