How to handle special cases in localization swift

后端 未结 3 402
一个人的身影
一个人的身影 2021-01-16 09:14

I created a Localizable.strings file and the translation works fine. But there is a special case where in english there is one word for singular and plural, like \'series\'.

3条回答
  •  佛祖请我去吃肉
    2021-01-16 09:40

    This is exactly what the Plural Rule Properties in Stringsdict files are for.

    So in addition to the "Localizable.strings" file you have to provide a "Localizable.stringsdict" property list file with plural rules for the language. In your case:

    Localizable.strings:

    "%ld series" = "%ld Serien";
    

    Localizable.stringsdict:

    
    
        %ld series
        
            NSStringLocalizedFormatKey
            %#@series@
            series
            
                NSStringFormatSpecTypeKey
                NSStringPluralRuleType
                NSStringFormatValueTypeKey
                ld
                one
                %ld Serie
                other
                %ld Serien
            
        
    
    
    

    Note that the proper format specifier for Int (which can be a 32-bit or 64-bit integer) is %ld.

    Now everything works "automatically", with no changes in the Swift code:

    for n in 1...3 {
        let str = String(format: NSLocalizedString("%ld series", comment: ""), n)
        print(str)
    }
    

    Output:

    1 Serie
    2 Serien
    3 Serien
    

    Even if more languages with other plural rules are added, no changes in the Swift code are necessary.

提交回复
热议问题