This article is written with XCode & Swift in mind. With that being said, notions & ideas explored below can be applied to any programming language / IDE. I leave that part as an exercise to the reader ;)

guard let templateString = NSLocalizedString("hello", tableName: "Greetings", comment: "") else { print("Missing localization"); return }

Sounds familiar ?

Let’s face it: Localization sucks. It’s all String-based. It’s messy. And even with the best effort put into arranging your .strings files, you always end-up forgetting which key to use, or with duplicates all over the place.

Not only that, but it’s also nearly impossible to keep track of changes made over time, since XCode won’t help you in the slightest if some key were to disappear or are otherwise renamed.

Now, what if I were to tell you there is a better way ? What if I told you the following is possible ?

label.text = Greetings.hello("world").localized()

// returns "Hello, world" in English,

// "Hallo, world" in German, etc.

And

Localization Managers

Before we do anything, we need to find a generic structure that can be reused for the many localized fields our app contains.

As with most things in programming, we’ll want some sort of Manager to make our logic reusable. At OneFit, I opted for a protocol which I called LocalizationManager

LocalizationManager protocol

As you can see, it’s quite straightforward. It also comes with its own convenient default implementation, which I’m sure you’re very familiar with.

The power of this protocol shines when you implement it with Enums; Swift Enums are among the most powerful and versatile of them all, and the perfect tool in this situation.

For instance, let’s say we are working on a shopping app, and have a few localized strings for the shopping cart. Given this example strings file:

LocalizedShoppingCart.strings

let’s declare the following ShoppingCartStrings Enum:

ShoppingCartStrings.swift

I’ve added the actual english values of these keys as documentation so that it shows up when we’re using auto-completion 👌

Now, that enum on its own is not going to do much. To fix that, all we need to do is to make it conform to LocalizationManager :

ShoppingCartStrings+LocalizationManager