Localizing text in Swift code
In this tutorial I want to show how to translate a text string in Swift code file to a different language.
Suppose you have an English text string in your .swift code:
let text = "Flat White"
The text can be internationalized with
let text = NSLocalizedString("Flat White", comment: "Coffee order name")
comment will be passed along with the text to translators. It is useful for describing the meaning of the text and/or the context it is used in.
I really like that we still have our original text “Flat White” in the code file instead of using identifiers. Thank you, Apple, I think this is more readable.
Exporting project for translation
Now let’s say we want to translate our project from English to Japanese. Choose
Export for Localization... menu when project is selected in Project Navigator. The text will be exported to
- Open the file and add a
target-language="jp"attribute to all the
<file original="project/InfoPlist.strings" source-language="en" target-language="jp" datatype="plaintext">
<target>element with translated text under the English
<trans-unit id="Flat White"> <source>Flat White</source> <target>フラットホワイト</target> <note>Coffee order name</note> </trans-unit>
Importing traslation back into the project
Import Localizations... menu and choose the
Finally, test the app with a different language
- Go to
- Choose a language form
Application Languagedrop down.
- Run your app.
Replacing parts of localized text
Often we want to replace the parts of the text string with dynamic values when the app is running. It can be done with
String.localizedStringWithFormat( NSLocalizedString("My name is %@. I am %d years old.", comment: "Greeting"), name, age)
Translator can change the order in which the populated arguments are copied into the string.
I am %$2@ years old and my name is %$1@.
Localizing lower and upper case text
Here is how to change the case of a string according to local rules.
"istanbul".localizedCapitalized // In Turkish: "İstanbul" "İstanbul".localizedLowercase // In Turkish: "istanbul" "istanbul".localizedUppercase // In Turkish: "İSTANBUL"
Localizing with Xcode 6: WWDC 2014 session video
What’s New in Internationalization: WWDC 2015 session video
About Internationalization and Localization: iOS Developer Library.