Neil Macy

Built-in Localisation in iOS

This is a fairly small thing, but really handy if you need it.

Localisation (in this case, translating your UI into another language, although localisation can also apply to things like changing layouts or images to suit a particular country) can add some overhead to your development process. You need to set your app up to use NSLocalizedStrings in the UI; you need to send those strings to someone who actually knows the language you're translating into; you need to test your changes in all supported languages to make sure the translation worked correctly, and makes sense in the context of the UI. (For more detail on how to localise strings, see this handy article on Hacking With Swift.)

There are little things baked into iOS which can help with this a little. One is UIBarButtonItem, which has an initialiser that takes a UIBarButtonItem.SystemItem parameter, which will let you specify the type of button without having to think about the actual text. For example, .done will use a translation of the word "Done" which is baked in. This means you get it with no extra effort, and it's also consistent across apps.

Another great example is in Locale. Locale has various methods whose name start with localizedString, for example localizedString(forRegionCode:). You can use this to get a translation of a country name. To see for yourself, paste this code into a new Playground:

func localisedName(for regionCode: String, using locale: Locale = Locale.current) -> String? {
    return locale.localizedString(forRegionCode: regionCode)

print(localisedName(for: "us") ?? "unknown country") // "United States"

print(localisedName(for: "fr", using: Locale(identifier: "de")) ?? "unknown country") "Frankreich"

So long as you know the region code for a given country, you can translate its name into the correct name for the system's current locale, or any other of your choice. And Locale even provides a list of all region codes: Locale.isoRegionCodes (although documentation is lacking; try printing it in a Playground). Wikipedia has a handy list of these ISO3166-2 codes, mapped to their English names.

Published on 10 July 2020