Search code examples
iosswift3nslocale

How to get country code using NSLocale in Swift 3


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.


Solution

  • See Wojciech N.'s answer for a simpler solution!


    Similarly as in NSLocale Swift 3, you have to cast the overlay type Locale back to its Foundation counterpart NSLocale in order to retrieve the country code:

    if let countryCode = (Locale.current as NSLocale).object(forKey: .countryCode) as? String {
        print(countryCode)
    }