Home > Software engineering >  How to create a Locale based on language code?
How to create a Locale based on language code?

Time:09-21

Currently, I am displaying language name, based on user settings locale

static func getDisplayLanguage(_ languageCode: String) -> String? {        
    let current = Locale.current

    return current.localizedString(forLanguageCode: languageCode)
}

But, now, I wish to display language name, based on the language locale, and independent from user settings locale.

For instance,

"es" (Spanish language code) will displayed as "Española"
"en" (English language code) will displayed as "English"
"zh" (Chinese language code) will displayed as "中文"
...

May I know, how I can achieve so?

CodePudding user response:

Simply change the locale declaration in your function to use the locale for the given language code

 let current = Locale(identifier: languageCode)

The whole function but compressed:

static func getDisplayLanguage(_ languageCode: String) -> String? {
    Locale(identifier: languageCode).localizedString(forLanguageCode: languageCode)
}
  • Related