T D Nguyen
T D Nguyen

Reputation: 7603

Wrong language code swift

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?

Upvotes: 1

Views: 958

Answers (3)

Rajamohan S
Rajamohan S

Reputation: 7269

Try below code,

let requiredString = pre.components(separatedBy: "-").first ?? pre //fr
/*if pre.contains("-"), then requiredString = before("-") else requiredString = pre*/

Upvotes: 4

vg0x00
vg0x00

Reputation: 608

print(Locale.components(fromIdentifier: Locale.preferredLanguages[0])["kCFLocaleLanguageCodeKey"]!)

this will print language code only.

Upvotes: 2

Mohamad Bachir Sidani
Mohamad Bachir Sidani

Reputation: 2099

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)

Upvotes: 1

Related Questions