7

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?

max82
  • 223
  • 3
  • 8

2 Answers2

12

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>
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • How would you translate the ```My friend %@ has``` part? – gpichler Feb 27 '23 at 17:11
  • @gpichler: I am not sure if I understand your question. You have one stringsdict file for every supported language. The German version would contain the entry `Mein Freund %@ hat %#@count@.` – Martin R Feb 27 '23 at 17:49
  • Hmm I think it's an issue with our translation tool then. It doesn't show the ```NSStringLocalizedFormatKey``` as translatable but only the `````` elements in the second dict. – gpichler Feb 27 '23 at 18:22
1

You are missing the format type key:

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

For more details on this, see String Format Specifiers

Andreas Oetjen
  • 9,889
  • 1
  • 24
  • 34
  • the "dogs" are not the problem, this is working. The problem is, that I don't know how to handle the name, because this shouldnt be changed in the stringsdict. – max82 Apr 13 '18 at 07:41