Swift String Localization
When developing applications meant for users around the globe, localization becomes a crucial aspect of your development process. Localization is the process of adapting your app to different languages and regions. In Swift, string localization is a fundamental part of making your app accessible to users who speak different languages.
What is String Localization?
String localization is the process of translating user-facing text in your application to different languages. Rather than hardcoding text directly in your Swift code, you store strings in separate resource files for each language you want to support.
Why Localize Strings?
- Reach a global audience by supporting multiple languages
- Improve user experience for non-native speakers
- Adapt content to cultural differences
- Meet App Store requirements for certain markets
Basic String Localization in Swift
Swift provides a simple yet powerful way to localize strings using the NSLocalizedString
function.
The NSLocalizedString Function
The basic syntax for localizing a string is:
let localizedString = NSLocalizedString("key", comment: "explanation for translators")
Let's see it in action:
// Instead of this:
let greeting = "Hello, world!"
// Do this:
let greeting = NSLocalizedString("greeting_text", comment: "Generic greeting shown on home screen")
When your app runs, iOS will automatically look up the corresponding translation for "greeting_text" in the appropriate language file based on the user's device settings.
Setting Up Localization in Your Project
1. Create Localizable.strings Files
First, you need to create a Localizable.strings
file:
- In Xcode, choose File > New > File...
- Select Strings File
- Name it
Localizable.strings
This will be your base language file (usually English).
2. Enable Localization
- Select your
Localizable.strings
file in the Project Navigator - In the File Inspector (right panel), click Localize...
- Choose your development language and click Localize
3. Add Languages
- Select your project file in the Project Navigator
- Select your target and go to the Info tab
- Under Localizations, click the + button
- Choose languages you want to support
Xcode will create localized versions of your Localizable.strings
file for each language.
4. Add Translations
Each Localizable.strings
file uses a simple key-value format:
"key" = "translated text";
For example, in your base Localizable.strings
(English):
"greeting_text" = "Hello, world!";
"welcome_message" = "Welcome to my app";
"login_button" = "Sign In";
In Localizable.strings
(Spanish):
"greeting_text" = "¡Hola, mundo!";
"welcome_message" = "Bienvenido a mi aplicación";
"login_button" = "Iniciar Sesión";
Advanced Localization Techniques
String Interpolation with Localization
To include variables in localized strings, use format specifiers:
// In Localizable.strings
"welcome_user" = "Welcome, %@!";
"items_count" = "You have %d items";
// In your Swift code
let username = "John"
let welcomeMessage = String(format: NSLocalizedString("welcome_user", comment: "Welcome message with username"), username)
let itemCount = 5
let itemsMessage = String(format: NSLocalizedString("items_count", comment: "Shows number of items"), itemCount)
Output (in English):
Welcome, John!
You have 5 items
Output (in Spanish, assuming translation):
¡Bienvenido, John!
Tienes 5 artículos
Handling Plurals with Stringsdict
For proper plural handling, use .stringsdict
files:
- Create a
Localizable.stringsdict
file (XML Property List) - Define plural rules for each language
Example Localizable.stringsdict
content:
<?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">
<dict>
<key>items_plural_format</key>
<dict>
<key>NSStringLocalizedFormatKey</key>
<string>%#@items@</string>
<key>items</key>
<dict>
<key>NSStringFormatSpecTypeKey</key>
<string>NSStringPluralRuleType</string>
<key>NSStringFormatValueTypeKey</key>
<string>d</string>
<key>zero</key>
<string>No items</string>
<key>one</key>
<string>1 item</string>
<key>other</key>
<string>%d items</string>
</dict>
</dict>
</dict>
</plist>
Then in your code:
let itemCount = 1
let message = String.localizedStringWithFormat(NSLocalizedString("items_plural_format", comment: ""), itemCount)
// Output: "1 item"
let itemCount2 = 0
let message2 = String.localizedStringWithFormat(NSLocalizedString("items_plural_format", comment: ""), itemCount2)
// Output: "No items"
Real-World Application: Building a Localized App
Let's create a simple localized greeting app:
import SwiftUI
struct ContentView: View {
// Get the current locale's language code
let currentLanguage = Locale.current.language.languageCode?.identifier ?? "en"
var body: some View {
VStack(spacing: 20) {
Text(NSLocalizedString("app_title", comment: "App title"))
.font(.largeTitle)
Text(String(format: NSLocalizedString("language_label", comment: "Shows current language"), currentLanguage))
.font(.headline)
Text(NSLocalizedString("greeting_message", comment: "Greeting message"))
.padding()
Button(NSLocalizedString("action_button", comment: "Main action button")) {
print(NSLocalizedString("button_pressed", comment: "Log message when button is pressed"))
}
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(10)
}
.padding()
}
}
And our Localizable.strings
file for English:
"app_title" = "Language Demo";
"language_label" = "Current language: %@";
"greeting_message" = "Welcome to our localized application!";
"action_button" = "Tap Me";
"button_pressed" = "Button was tapped!";
For Spanish (es.lproj/Localizable.strings
):
"app_title" = "Demostración de Idioma";
"language_label" = "Idioma actual: %@";
"greeting_message" = "¡Bienvenido a nuestra aplicación localizada!";
"action_button" = "Tócame";
"button_pressed" = "¡Se tocó el botón!";
Best Practices for String Localization
- Never hardcode user-facing strings - Always use
NSLocalizedString
- Use descriptive keys - Make keys semantically meaningful (e.g.,
login_button_text
instead ofbutton1
) - Add helpful comments - Give context to translators through the comment parameter
- Be mindful of string length - Some languages may require more space than others
- Test with pseudo-localization - To catch potential issues early
- Consider cultural differences - Some phrases or symbols may have different meanings in different cultures
- Extract all strings early - Don't wait until the end of development to localize
Common Mistakes to Avoid
- Forgetting to localize strings in SwiftUI's
Text
views - Concatenating strings for sentences (use format strings instead)
- Ignoring right-to-left languages
- Not accounting for pluralization rules
- Hardcoding date and number formats
Testing Localized Strings
To test your localized strings:
- In the Simulator, go to Settings > General > Language & Region
- Select a different language and region
- Restart your app to see the changes
Alternatively, you can set the App Language in the Scheme Editor:
- In Xcode, select Product > Scheme > Edit Scheme...
- Under Run > Options, set Application Language
Summary
String localization is essential for making your Swift apps accessible to a global audience. By using NSLocalizedString
and organizing translations in Localizable.strings
files, you can easily adapt your app for users who speak different languages.
We've covered:
- Basic string localization with
NSLocalizedString
- Setting up localization in your project
- Handling variables and plurals in localized strings
- Real-world application of localization
- Best practices and common mistakes
By implementing proper string localization from the beginning of your development process, you'll create a more inclusive app experience and potentially reach a much wider audience.
Additional Resources
- Apple's Localization Guide
- Human Interface Guidelines for Localization
- WWDC Video: Localizing Your App
Exercises
- Create a simple app with at least 10 user-facing strings and localize it for two languages.
- Implement a language switcher that allows users to change languages within the app.
- Create a localized app that properly handles plurals for counting items.
- Test your app with right-to-left languages like Arabic or Hebrew.
- Research and implement localization for dynamic content loaded from an API.
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)