1

I set the language of the simulator to French. To check the language code, I used a couple of solutions:

let lang = NSLocale.autoupdatingCurrent.languageCode
print(lang)

let pre = Locale.preferredLanguages[0]
print(pre)

The result are:

Optional("en")
fr-US

What I expected to get is:

fr

How can I achieve that?

T D Nguyen
  • 7,054
  • 4
  • 51
  • 71

3 Answers3

4

Try below code,

let requiredString = pre.components(separatedBy: "-").first ?? pre //fr
/*if pre.contains("-"), then requiredString = before("-") else requiredString = pre*/
Rajamohan S
  • 7,229
  • 5
  • 36
  • 54
2
print(Locale.components(fromIdentifier: Locale.preferredLanguages[0])["kCFLocaleLanguageCodeKey"]!)

this will print language code only.

vg0x00
  • 588
  • 4
  • 11
1

If you want the Language instead of the Language_Region, then I suggest to take the sub string before the _ from the string to neglect the Region.

(If the string contains no _ then take the entire string since it doesn't contain the region in it)

Mohamad Bachir Sidani
  • 2,077
  • 1
  • 11
  • 17