V. Khuraskin
V. Khuraskin

Reputation: 89

SWIFT Using Stringsdict and Plural Rule

In my iOS app on one of the screens I use a label, the text on which should change depending on the number of objects: one apple, two appleS and others.. I created Localizable.stringdict file:

<?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>searches</key>
<dict>
    <key>NSStringLocalizedFormatKey</key>
    <string>%#@search_count@</string>
    <key>search_count</key>
    <dict>
        <key>NSStringFormatSpecTypeKey</key>
        <string>NSStringPluralRuleType</string>
        <key>NSStringFormatValueTypeKey</key>
        <string>s</string>
        <key>one</key>
        <string>остался %s поиск</string>
        <key>many</key>
        <string>осталось %s поиска</string>
        <key>other</key>
        <string>осталось %s поиска</string>
    </dict>
</dict>

Later in the viewController class, I created a function

  private func searches(_ count: UInt) {
     let format: String = NSLocalizedString("searches", comment: "")
     let result: String = String.localizedStringWithFormat(format, count)
     print(result)
  }

and call this function in viewDidLoad.

The application crashes at the start with error Thread 1: EXC_BAD_ACCESS (code=1, address=0x0).

Debbuger indicates the line where Result is created. As far as I understand the problem is that the Format is not created.

How can this problem be solved?

Upvotes: 0

Views: 1639

Answers (1)

Martin R
Martin R

Reputation: 539735

Your dictionary specifies “s” as string format specifier, that is for a C string. For UInt (which is NSUInteger as Foundation C type) it should be “lu” instead (compare String Format Specifiers):

<key>NSStringLocalizedFormatKey</key>
<string>%#@search_count@</string>
<key>search_count</key>
<dict>
    <key>NSStringFormatSpecTypeKey</key>
    <string>NSStringPluralRuleType</string>
    <key>NSStringFormatValueTypeKey</key>
    <string>lu</string>
    <key>one</key>
    <string>остался %lu поиск</string>
    <key>many</key>
    <string>осталось %lu поиска</string>
    <key>other</key>
    <string>осталось %lu поиска</string>
</dict>

Upvotes: 3

Related Questions