User Language Preferences

Here’s a quick one. Google has a neat library for (among lots of other things) on-device translation, called ML Kit. I’m trying to implement it for a hackathon. Turns out (no surprise?) it’s written in Objective-C, and doesn’t really have great affordances to integrate with system libraries. In particular, the enum called TranslateLanguage doesn’t have an initializer that takes a language identifier or locale identifier. I went about this in what I thought was the obvious way, using Locale.current.languageCode to initialize a new TranslateLanguage. But of course the current locale isn’t necessarily the same as the language the user has chosen. For that, I found this to be the simplest way:

extension TranslateLanguage {
    init?() {
        guard let preferredLanguage = Locale.preferredLanguages.first,
              let languageCode = Locale(identifier: preferredLanguage)
              .languageCode else { return nil }
        self = .init(rawValue: languageCode)

About Joel Kin

Developing on Apple platforms for, holy shit, like twenty years now. Find me on linkedin and twitter. My personal website is
This entry was posted in Code. Bookmark the permalink.