Search code examples
swiftmacoslocalization

Language codes to friendly names


I have a language code, such as "en_US", and I'm trying to get a friendly name from it such as "English".

Here's what I'm doing right now:

Locale.current.localizedString(forLanguageCode: code)

It works, but for languages such as Chinese, it doesn't quite do what I want.

zh-Hans should return "Simplified Chinese", and zh-Hant should return "Traditional Chinese".

However, they both just return "Chinese". How would you get them to return the correct values?


Solution

  • You can use NSLocale's displayName(forKey:value:) instead.

    let code = "en_US"
    if let identifier = (Locale.current as NSLocale).displayName(forKey: .identifier, value: code) {
        print(identifier) /// English (United States)
    }
    
    let code = "zh_Hans"
    if let identifier = (Locale.current as NSLocale).displayName(forKey: .identifier, value: code) {
        print(identifier) /// Chinese, Simplified
    }