I need to add multi-language support in an iOS app that is written in Xcode using Swift. I need to localize
Such as below in Android we add named strings and plurals in XML files:
<string name="static_string">Hello world!</string>
<string name="placeholder_string">You have %2$d new messages.</string>
<plurals name="plural_string">
<item quantity="one">You have a new message.</item>
<item quantity="other">You have %2$d new messages.</item>
</plurals>
And following Java to get strings programmatically:
res.getString(R.string.placeholder_string, mailCount)
res.getQuantityString(R.plurals.plural_string, mailCount, mailCount)
I am looking for the solution corresponding to Swift (iOS)
Setup project Localizations
, as shown in screenshot the project has English and Russian languages.
1: Create a file named Localizable.strings
and add following lines
static_string="Hello world!";
placeholder_string="You have %d new messages.";
2: We define Plurals in a separate file, lets create a file named Localizable.stringsdict
and paste following:
<?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">
<!-- FIRST PLURAL STRING -->
<dict>
<key>plural_string</key>
<dict>
<key>NSStringLocalizedFormatKey</key>
<string>%#@value@</string>
<key>value</key>
<dict>
<key>NSStringFormatSpecTypeKey</key>
<string>NSStringPluralRuleType</string>
<key>NSStringFormatValueTypeKey</key>
<string>d</string>
<key>one</key>
<string>You have a new message.</string>
<key>other</key>
<string>You have %d new messages.</string>
</dict>
</dict>
</dict>
<!-- NEXT PLURAL STRING -->
</plist>
Next, localize Localizable.stringsdict
file, see in screenshot, the file is localized for English and Russian languages:
Usage:
NSLocalizedString("static_string", comment: "") // Hello world!
String(format: NSLocalizedString("placeholder_string", comment: ""), 5) // You have 5 new messages.
let plural = NSLocalizedString("plural_string", comment: "")
String(format: plural, 1) // You have a new message.
String(format: plural, 2) // You have 2 new messages.
Plural Rules: In XML code, notice <key>one</key>
and <key>other</key>
, here you can use zero
, one
, two
, few
, many
, other
depending on the language and your requirements.
Use following link for more information on language specific plural rules: http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html
Also this article will help if you are new to string formatting https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html