How to get country code using NSLocale in Swift 3

digidhamu picture digidhamu · Sep 20, 2016 · Viewed 43.2k times · Source

Could you please help on how to get country code using NSLocale in Swift 3 ?

This is the previous code I have been using.

NSLocale.currentLocale().objectForKey(NSLocaleCountryCode) as! String

I can get Language Code as below in Swift 3.

Locale.current.languageCode!

As I can see, fetching languageCode is straight forward but countryCode property is not available.

Answer

Wojciech Nagrodzki picture Wojciech Nagrodzki · Sep 29, 2016

You can use regionCode property on Locale struct.

Locale.current.regionCode

It is not documented as a substitute for old NSLocaleCountryCode construct but it looks like it is. The following code checks countryCodes for all known locales and compares them with regionCodes. They are identical.

public func ==(lhs: [String?], rhs: [String?]) -> Bool {
    guard lhs.count == rhs.count else { return false }

    for (left, right) in zip(lhs, rhs) {
        if left != right {
            return false
        }
    }

    return true
}

let newIdentifiers = Locale.availableIdentifiers
let newLocales = newIdentifiers.map { Locale(identifier: $0) }
let newCountryCodes = newLocales.map { $0.regionCode }

let oldIdentifiers = NSLocale.availableLocaleIdentifiers
newIdentifiers == oldIdentifiers // true

let oldLocales = oldIdentifiers.map { NSLocale(localeIdentifier: $0) }
let oldLocalesConverted = oldLocales.map { $0 as Locale }
newLocales == oldLocalesConverted // true

let oldComponents = oldIdentifiers.map { NSLocale.components(fromLocaleIdentifier: $0) }
let oldCountryCodes = oldComponents.map { $0[NSLocale.Key.countryCode.rawValue] }
newCountryCodes == oldCountryCodes // true