Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: plurals and custom locale

I'm developing app that supports "en" and "ru" languages, users can select language inside app.

If default phone's locale set to "en", but inside app selected "ru" language, then when trying to localize plural sentence ignored 'many'/'few' form. So it's localized by the English plural rules.

Definition:

<key>%d files</key>
    <dict>
        <key>NSStringLocalizedFormatKey</key>
        <string>%#@files@</string>
        <key>files</key>
        <dict>
            <key>NSStringFormatSpecTypeKey</key>
            <string>NSStringPluralRuleType</string>
            <key>NSStringFormatValueTypeKey</key>
            <string>d</string>
            <key>one</key>
            <string>один файл</string>
            <key>many</key>
            <string>%d файлов</string>
            <key>other</key>
            <string>%d файла</string>
        </dict>
    </dict>

Code to localize (manually create 'ru' locale):

let locale = NSLocale(localeIdentifier: "ru_RU")
String(format: NSLocalizedString("%d files", comment: ""),
                    locale: locale,
                    count)

As output i got:
for count = 1: "один файл" - and it's right
for count = 2: "2 файла" - it's also right (from category 'other')
for count = 6: "6 файла" - wrong, also from category 'other', but should be taken from 'many'

If i switch phone's language to Russian, then all being localized correctly.

like image 677
Mikhail Avatar asked Oct 31 '22 11:10

Mikhail


2 Answers

You should use keys:

one for 1 = один файл

few for 2-4 = 2 файла

other for all other cases

like image 133
Thorax Avatar answered Nov 12 '22 17:11

Thorax


It is quite old question, but I've faced the same problem and this is how I fixed this:

let path = Bundle.main.path(forResource: "ru", ofType: "lproj")!
let bundle = Bundle(path: path)!
let localizedString = String(format: NSLocalizedString("%d files", bundle: bundle, comment: ""),
                                     locale: NSLocale(localeIdentifier: "ru_RU"),
                                     count)

The main idea is to make NSLocalizedString to search in language-specific bundle.

like image 45
Accid Bright Avatar answered Nov 12 '22 15:11

Accid Bright