Typed translation constants, a missing core iOS feature

As iOS developer, we all know how hard localization is out of the box. We have all translations available inside .strings files. A separate file for each supported language.

The Typed Translations SPM package will assist you with the generation of code from your base language .strings file.

Possible scenarios

  • For small projects, the master localization data is just in your repository.
  • For larger projects however, the master data is most likely maintained by a third party solution for easy management of this data by copywriters. They can manage the values via a website and developers just download the latest state via an API.

In code, you will most likely see a very unswifty syntax to get the correct value for a certain translation key.

Inside regular code bases, you will see a lot of lines pop up like this:

NSLocalizedString("close", tableName: "Localizable", bundle: .main, value: "close", comment: "")

To make code a little bit more swifty, an extension could be created so you end up with the following code which reads a lot better.

extension String {
    func localized(bundle: Bundle = .main, tableName: String = "Localizable") -> String {
        NSLocalizedString(self, tableName: tableName, bundle: bundle, value: self, comment: "")

Issues with this approach

By coding like this, you will encounter a lot of issues. The larger the project, the more issues to expect. This approach is labour intensive because no intellisense on key name and error prone.

When you download the latest version of the .strings file from your third party tool. It will always be a surprise what is broken. Did someone delete a specific key, or did someone just fix a typo in the name of the key. Or did someone add or remove a parameter format (%@,…) to the string. Or did someone forgot to add the keys with values while adding a new feature. So much to go wrong…

That’s where the power of this Typed Translations SPM package comes in handy!

With this simple light weight solution to generate constants from a .strings file, you can start writing code like this:

Localizations.welcomeText("John Doe")

Since the swift package is generating an executable, you could easily run the script yourself for small projects or integrate it in your development pipeline in larger projects. If you integrate a similar approach in your codebase, you could be surprised how many small localisation issues you have and did not know.

Known issue

A small issue with this approach is that you don’t get compiler feedback when you had 3 format values and removed one from it. That behaviour stays the same as the original native implementation. On the other hand, we stay still very close to the original method String.localizedStringWithFormat() by just passing on the same arguments and support all formats out of the box with minimal complexity introduced.