Design Converter
Education
Software Development Executive - III
Last updated on May 24, 2024
Last updated on May 24, 2024
Localization is the process that adapts an app to support multiple languages and regions, enabling it to cater to a global audience. At the core of this process is the Swift localized string, an essential component in creating apps that offer a rich user experience in their native language.
In this blog, we will embark on a journey to understand how to implement and manage Swift localized string in our applications.
Swift's string localization capability allows us to extract user-facing strings from our code and place them into separate "strings files." These files hold key-value pairs where the key represents a unique identifier for each string, and the value is the string itself in a specific language. By localizing strings, developers ensure that their apps are not only accessible but also culturally relevant to users from different parts of the world.
Localization in Swift involves using the Localizable.strings swift file – a plain text file that Xcode uses to match strings in your app with their respective translations. Within this file, each localized string is represented by a key-value pair, where the key is a string key that serves as an identifier and is used in your code, while the value is the actual string content presented to the user in their native language.
Here's the typical flow for localizing a string in Swift:
You have to use the NSLocalizedString function in your code passing the string key and a comment for translators.
Xcode looks up the key in the Localizable.strings file for the current language setting.
If the key exists, the corresponding translated string is used; otherwise, the default language string is displayed.
For example, your default strings file for English might look like this:
1/* A greeting message shown on home screen */ 2"Greeting_Text" = "Hello, welcome to our app!";
During run-time, if a user's app language is set to Spanish and you have a Spanish Localizable.strings file, Xcode will look for the same string key and display the Spanish version of your string:
1/* El mensaje de saludo mostrado en la pantalla principal */ 2"Greeting_Text" = "¡Hola, bienvenido a nuestra aplicación!";
This simple yet powerful system allows developers to cater to different languages without altering the logic of their code.
To configure your project for localizing strings, follow these steps:
Launch your Xcode project and select your app target in the project navigator.
Click on the Info tab and look for "Localizations" in the project settings.
Click the + button to add a new language. For example, if you are adding French localization, this will create a new fr.lproj folder in your project.
Opt for the file types you want to localize, whether it is the storyboard, XIB files, or the Localizable.strings file.
Here's an example of how to get started with a new Localizable.strings file:
In the project navigator, right-click and choose "New File."
Select the "Strings" file and name it Localizable.strings.
Make sure that the file is added under the correct localization folder (e.g., fr.lproj for French).
In the file inspector on the right, under the Localize button, check the box for the languages you want to include for localization.
At this point, you will have separate Localizable.strings files for each language you added. For instance, you'll have a Localizable.strings (English) in the en.lproj folder for English and a Localizable.strings (French) in the fr.lproj folder for French. Now you can begin adding key-value pairs to each localized strings file.
Here's an example of adding entries to your English Localizable.strings file:
1/* Title for the home screen */ 2"HomeScreen_Title" = "Home"; 3/* Message when data is successfully downloaded */ 4"DataDownload_Success" = "Your data has been successfully downloaded.";
And in the French Localizable.strings file, the translated strings would look like this:
1/* Titre de l'écran d'accueil */ 2"HomeScreen_Title" = "Accueil"; 3/* Message lorsque les données sont téléchargées avec succès */ 4"DataDownload_Success" = "Vos données ont été téléchargées avec succès.";
After adding entries to the Localizable.strings files, the next step is to localize these entries in your Swift code.
To use the Swift localized string in your code, you apply the NSLocalizedString function to retrieve the correct string for the current language setting. Each NSLocalizedString takes a string key and an optional comment for translators or to provide context about where and how the string is used in the app.
Here is an example of how to use NSLocalizedString in Swift:
1let homeTitle = NSLocalizedString("HomeScreen_Title", comment: "Title for the home screen") 2let successMessage = NSLocalizedString("DataDownload_Success", comment: "Data download success message")
The advantage of using NSLocalizedString is that it automatically looks up the string key in the Localizable.strings file localizable, corresponding to the current language setting of the app. If a corresponding key is not found, it defaults to the string provided as the key itself, allowing the app to continue running without crashing due to missing strings.
In your code, use these localizable strings wherever you previously had static string literals. For UI components, such as buttons and labels, assign the localized strings directly to their text properties, like so:
1homeButton.setTitle(NSLocalizedString("HomeScreen_Title", comment: "Title for the home button"), for: .normal)
As your app grows, you'll find yourself managing multiple strings files for different localizations. This can quickly become cumbersome, but there are ways to make the process more manageable:
• Organize your keys: Group and prefix your keys by the interface component or feature they are associated with, which helps in finding and updating the localized strings.
• Use version control: Track changes to your strings file using version control systems like Git. This can help manage changes as your apps and their localizations evolve.
• Explore third-party tools: There are multiple tools available that can help you manage and automate the localization process. These tools can streamline adding languages, editing strings, and pushing updates to your project.
Throughout this process, regularly review and update your localized strings, paying attention to any content changes or added features that might require additional localizations.
To maintain a scalable and efficient localization system within your Swift project, keep the following best practices in mind:
• Consistency: Use similar phrases for the same ideas to make it easier for translators and maintain consistency across your app's language support.
• Comments: Provide clear, helpful comments when using NSLocalizedString. These comments should give translators context for the use of each string.
• Avoid Concatenation: Build sentences in such a way that you minimize the use of string interpolation or concatenation to piece together user interface elements. Different grammatical rules in languages can make this approach error-prone.
• Plurals and Formatting: Account for plural forms and string formatting rules, which can differ greatly between languages. Xcode's localized strings dict file format supports different plural categories and formatting rules for this very purpose.
By following these practices, you ensure that all your localizable strings are accessible, organized, and easy to manage, no matter how many languages your app wants to support.
Implementing Swift localized string is a vital step towards building apps that resonate with users globally. By understanding and utilizing the tools and best practices for Swift localization strings, developers can create apps that not only function in multiple languages but also offer native-language experiences that can increase user engagement.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.