.stringsdict files were added in iOS 7 and OS X 10.9. They allow us to "pluralize" text in our app without a bunch of switch
or if
statements.
let spaceships = [Spaceship(selected: true)]
let pluralized = String.localizedStringWithFormat(
NSLocalizedString("%d ships selected",
comment: "how many ships selected"),
spaceships.filter { $0.selected }.count
)
The localizedStringWithFormat
function is terribly smart.
It will look for a Localizable.stringsdict file before returning and query it for the correct format string to use before returning our final formatted string.
A Localizable.stringsdict is really just a .plist file with a few special strings in it.
We can create a Localizable.stringsdict file either completely by hand in a text editor, or by adding a new Property List to our project and naming it Localizable.stringsdict.
Now that we have a .stringsdict file, let's use it.
The root key is the same one we passed into NSLocalizedString.
Then, we define a sort of string-replacement-variable using some special characters: %#@VARIABLE_NAME_HERE@
. The system will then find the sub-dictionary that shares a name with this variable, and use it to pluralize.
We can provide cases for zero
, one
, two
, few
, many
, and other
. Each potential plural case is optional for each language, except other
.
Download an example project showing off this functionality here.
Hat tip to Matthew Bischoff for the idea for today's Bite, which actually inspired a whole series of localization Bites with more still to come!