Let’s immediately localize our projects

New project? Whether you need it or not, start localizing immediately. It does not matter that your app is only in English at launch, sooner or later, you’ll need to internationalize your app. So you’ll only see the benefits later, when you are app picks up and you suddenly find the need to translate it.

Good news, with a few simple tricks that can be started when the project is created or soon after:

  • you won’t have to open all your screens one by one to find what needs to be localized, it’s already done
  • you will find all localized strings in your catalog, ready to be sent to somebody for translation
  • bonus: if you work for a company, impress your boss by giving a ridiculously low estimate for how much time it will take to localize, the work was done incrementally, and it’s not going to be a huge project to support a new language

Add a String Catalog to your project

In the file explorer of Xcode, right-click in your Resources or Supporting Files folder, click “New File…”, and add a String Catalog called “Localizable”.

That’s it, you are ready to localize.

Adopt a naming convention for your keys

Keep it simple, my keys are always structured the same, with a bit of consistency, you will make it easy to find what you want, and maintain your project.

The convention I recommend is:

  • the first segment is the name of the screen
  • each segment gets more specific about where the string is going to be used and what it represents
  • each segment of your key is written using snake_case
  • segments are separated by a dot .

For example:

  • “editor.title” represents the title of the Editor screen
  • “editor.add_frame_button.title” represents the title within

Write a shorthand to transform a key into a localized string

Writing NSLocalizedString every time you need it and adding a comment isn’t. It’s dead simple, start by creating a new String+i18n.swift file.

Add a basic extension to transform a string into a localized string:

import Foundation

extension String {
    var i18n: String { NSLocalizedString(self, comment: "") }
}

And then to use it in code:

func viewDidLoad() {
    super.viewDidLoad()

    // i18n
    title = "editor.title".i18n // Editor
    addFrameButton.setTitle("editor.add_frame_button.title".i18n, forState: .normal) // Add Frame
}

And that’s pretty much it. Never hardcode an interface string and always use your shorthand function to localizable each and every string, it’s an overhead of approximately 30 seconds per screen that will benefit you in the long run. This will work with UIKit & SwiftUI.


Leave a Reply

Your email address will not be published. Required fields are marked *