Skip to main content

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:

swift
let localizedString = NSLocalizedString("key", comment: "explanation for translators")

Let's see it in action:

swift
// 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:

  1. In Xcode, choose File > New > File...
  2. Select Strings File
  3. Name it Localizable.strings

This will be your base language file (usually English).

2. Enable Localization

  1. Select your Localizable.strings file in the Project Navigator
  2. In the File Inspector (right panel), click Localize...
  3. Choose your development language and click Localize

3. Add Languages

  1. Select your project file in the Project Navigator
  2. Select your target and go to the Info tab
  3. Under Localizations, click the + button
  4. 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:

swift
// 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:

  1. Create a Localizable.stringsdict file (XML Property List)
  2. Define plural rules for each language

Example Localizable.stringsdict content:

xml
<?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:

swift
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:

swift
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

  1. Never hardcode user-facing strings - Always use NSLocalizedString
  2. Use descriptive keys - Make keys semantically meaningful (e.g., login_button_text instead of button1)
  3. Add helpful comments - Give context to translators through the comment parameter
  4. Be mindful of string length - Some languages may require more space than others
  5. Test with pseudo-localization - To catch potential issues early
  6. Consider cultural differences - Some phrases or symbols may have different meanings in different cultures
  7. Extract all strings early - Don't wait until the end of development to localize

Common Mistakes to Avoid

  1. Forgetting to localize strings in SwiftUI's Text views
  2. Concatenating strings for sentences (use format strings instead)
  3. Ignoring right-to-left languages
  4. Not accounting for pluralization rules
  5. Hardcoding date and number formats

Testing Localized Strings

To test your localized strings:

  1. In the Simulator, go to Settings > General > Language & Region
  2. Select a different language and region
  3. Restart your app to see the changes

Alternatively, you can set the App Language in the Scheme Editor:

  1. In Xcode, select Product > Scheme > Edit Scheme...
  2. 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

Exercises

  1. Create a simple app with at least 10 user-facing strings and localize it for two languages.
  2. Implement a language switcher that allows users to change languages within the app.
  3. Create a localized app that properly handles plurals for counting items.
  4. Test your app with right-to-left languages like Arabic or Hebrew.
  5. 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! :)