Advanced Localization Technique for Enums in iOS development

When implementing internationalization for your iOS apps, you might find yourself repeating some code; you can make your life easier by using a computed property such as .localized, that returns the localized String, that’s cleaner and understandable.

In this Article I’ll layout an advanced technique you can use in Enums, such as the List of Restaurant Categories, Languages, or Countries. I’ll assume you already have your project set up for localization.

Now Enums are a powerful way to add list such as these, since you have access to protocols such as CaseIterable, where you can call MyEnum.allCases to get an array of all the cases there are.

What’s the technique?, using Enum’s raw representation ability and pass it as an argument in NSLocalizedString, and doing so in a protocol to conform our Enums to this protocol and get the functionality.

Localizable Protocol

This protocol, and it’s extension, provide the base functionality of this technique, where all conforming Enums acquire the .localized computed property, now we need Localizable to have an Associated Raw Value type of StringProtocol, so our Enum’s raw value property can be called.

Notice that we are managing all the Localization functionality in one place, applying the Dry Principle.

A sample Enum

Since the enum conforms to String, we need each case to have a string value, Localizable uses it as Raw Value

Usage

Now we can simply call Language.english.localized to get the corresponding translation of English to the target language, such as Spanish — Inglés, or French — Anglais, making a Language Selector List much more easy to make.

Having our Enums conform to Localizable, allows us to implement other protocols very easily, such as CaseIterable, and Identifiable, making SwiftUI development way faster and cleaner, here’s an example:

NOTE that For Each doesn’t have a ID argument, since our Enums are Identifiable, making it very clean and elegant. Now we have a complete list that automatically localizes the enums iterations.

Software Entrepreneur