If you are already familiar with localizing plurals in iOS and you are just looking to remember the specifics, the cheat sheet below will help you out.

If you are new to this, skip the cheat sheet for now and read the basics below.

Cheat sheet

Image for post

Basics

Every time you want to localize texts like My dog ate 2 carrots where the carrot count is dynamic, one localization string will not be enough. For example, localizing with My dog ate %i carrots would produce My dog ate 1 carrots when passing in 1.

The first solution that may come to your mind could be to create another localization string for one carrot and adding some logic to your code like:

if carrotCount == 1 { 
   label.text = NSLocalizedString("dog_eating_carrots_one") 
} else { 
   label.text = String(format:       NSLocalizedString("dog_eating_carrots_multiple"), carrotCount) 
}

This solution may work for some languages, but different languages vary in how they handle plurals. For example, in Russian you would have to handle more cases. Plural rules for the word dog look like this:

  • собака for 1, 21, 31, 41, 51, 61 etc. Examples: 1 собака, 21 собака
  • собаки for 2-4, 22-24, 32-34 etc. Examples: 2 собаки, 22 собаки
  • собак for 5-20, 25-30, 35-40 etc. Examples: 5 собак, 20 собак

It would be complicated to handle this logic in code. So here comes Localizable.strigsdict to the rescue.

Unlike a Localizable.strings file, a Localizable.strigsdict file provides additional features to work with different languages, for example to define plural rules. The Localizable.strigsdict is able to interpret the arguments you pass in and select the right localized string based on it.

Creating and localizing a Localizable.stringdict file

To create a Localizable.stringdict file select a .stringdict template from Xcode’s dialog when creating a new file.

Image for post

The localization process is exactly the same as for Localizable.stringsfiles. If you are new to localization in iOS in general, you can catch up by reading Paul Hudson’s article on this topic.

#swift #ios-app-development #xcode #ios #localization

Step-by-step guide for localizing plurals in iOS
3.90 GEEK