25

I have found the answer for this for objective-c but Im having a hard time doing this in swift.

I have used this to get the country code for the current location:

     let countryCode = NSLocale.currentLocale().objectForKey(NSLocaleCountryCode) as! String
    print(countryCode)
// printing for example US

But how do I convert this country code to a country name, like in this example converting "US" to "United States"?

2

9 Answers 9

50

A super clean Swift 3 version would be:

func countryName(countryCode: String) -> String? {
    let current = Locale(identifier: "en_US")
    return current.localizedString(forRegionCode: countryCode)
}

You can change the locale identifier to eg. Locale.current.identifier if you want localized names. The example above is for English only.

3
  • 1
    So far this is by far the best answer for Swift 3 and later. Though the ?? nil is pointless.
    – rmaddy
    Oct 11, 2018 at 22:09
  • Works perfectly on Swift 5.1
    – LondonGuy
    Oct 22, 2019 at 22:44
  • 1
    Or you can just do Locale.current.localizedString(forRegionCode: countryCode)
    – Islam
    Nov 27, 2023 at 17:47
39

Swift 3

func countryName(from countryCode: String) -> String {
    if let name = (Locale.current as NSLocale).displayName(forKey: .countryCode, value: countryCode) {
        // Country name was found
        return name
    } else {
        // Country name cannot be found
        return countryCode
    }
}
4
  • There's no need to use NSLocale in Swift 3.
    – rmaddy
    Mar 23, 2018 at 23:19
  • @rmaddy - Then post an alternative without an NSLocale dependency. Oct 11, 2018 at 21:57
  • 2
    @RobertGummesson See the answer by Daniel.
    – rmaddy
    Oct 11, 2018 at 22:04
  • @rmaddy - Right, missed that one. ...and I agree with your comment about nil. Oct 12, 2018 at 13:04
9

Try doing something like this:

// get the localized country name (in my case, it's US English)
let englishLocale = Locale.init(identifier: "en_US")

// get the current locale
let currentLocale = Locale.current

var theEnglishName : String? = englishLocale.displayName(forKey: NSLocaleIdentifier, value: currentLocale.localeIdentifier)
if let theEnglishName = theEnglishName
{
    let countryName = theEnglishName.sliceFrom("(", to: ")")
    print("the localized country name is \(countryName)")
}

with this helper function that I found here:

import Foundation

extension String {
    func sliceFrom(start: String, to: String) -> String? {
        return (rangeOfString(start)?.endIndex).flatMap { sInd in
            (rangeOfString(to, range: sInd..<endIndex)?.startIndex).map { eInd in
                substringWithRange(sInd..<eInd)
            }
        }
    }
}

I figured this out by researching into this related question.

1
  • This answer definitely works but on the top part Swift 4.2 doesn't have a 'sliceFrom' function anymore. Instead use 'replacingOccurrences' like so: theEnglishName.replacingOccurrences(of: "(", with: "").replacingOccurrences(of: ")", with: ""). stackoverflow.com/a/53839473/4833705 Dec 18, 2018 at 19:02
6

Here is a compact swift 4 version that has been working for me:

func countryCode(from countryName: String) -> String? {
    return NSLocale.isoCountryCodes.first { (code) -> Bool in
        let name = NSLocale.current.localizedString(forRegionCode: code)
        return name == countryName
    }
}

or an elegant extension like @Memon suggests:

extension Locale {

    func countryCode(from countryName: String) -> String? {
        return NSLocale.isoCountryCodes.first { (code) -> Bool in
            let name = self.localizedString(forRegionCode: code)
            return name == countryName
        }
    }

}
1

If you want to print the country name and country flag here is the code

func countryInformation(countryCode:String){
        
        var flag: String? = ""
        let flagBaseCode = UnicodeScalar("🇦").value - UnicodeScalar("A").value
        countryCode.uppercased().unicodeScalars.forEach {
            if let scaler = UnicodeScalar(flagBaseCode + $0.value) {
                flag?.append(String(describing: scaler))
            }
        }
        if flag?.count != 1 {
            flag = nil
        }
        
        let countryName = Locale.current.localizedString(forRegionCode: countryCode)
        print(countryName ?? "No name")
        print(flag ?? "No flag")
        print(countryCode)
        
    }

How to use

let regionCode = Locale.current.regionCode ?? "ae"
countryInformation(countryCode: regionCode)

Output will be:

United Arab Emirates
🇦🇪
AE
0

Try this

let countryLocale : NSLocale =  NSLocale.currentLocale()
            let countryCode  = countryLocale.objectForKey(NSLocaleCountryCode)// as! String
            let country = countryLocale.displayNameForKey(NSLocaleCountryCode, value: countryCode!)
            print("Country Locale:\(countryLocale)  Code:\(countryCode) Name:\(country)")
0

Working on Swift3

import Foundation

  extension String {
      func sliceFrom(start: String, to: String) -> String? {
           return (range(of: start)?.upperBound).flatMap({ (sInd) -> String? in
                   (range(of: to, range: sInd..<endIndex)?.lowerBound).map { eInd in
                      substring(with: sInd..<eInd)
         } 
     })
    }
   }   

Use in app delegate

        let englishLocale : NSLocale = NSLocale.init(localeIdentifier :  "en_US")

    // get the current locale
    let currentLocale = NSLocale.current

    var theEnglishName : String? = englishLocale.displayName(forKey: NSLocale.Key.identifier, value: currentLocale.identifier)
    if let theEnglishName = theEnglishName
    {
        countryName = theEnglishName.sliceFrom(start: "(", to: ")")
        print("the localized country name is \(countryName)")
    }
1
  • Do not use NSLocale in Swift 3.
    – rmaddy
    Mar 23, 2018 at 23:19
0

Swift 4

struct CountryCode {
    let country: String?
    let code: String
}

let countries: [CountryCode] = NSLocale.isoCountryCodes.map { 
    let country = (Locale.current as NSLocale).displayName(forKey: .countryCode, value: $0)
    return CountryCode(country: country, code: $0) 
}

countries.map { print($0) }

// Prints 
// CountryCode(country: Optional("Ascension Island"), code: "AC")
// CountryCode(country: Optional("Andorra"), code: "AD")
// CountryCode(country: Optional("United Arab Emirates"), code: "AE")
// CountryCode(country: Optional("Afghanistan"), code: "AF")
1
  • Do not use NSLocale in Swift 3 or 4. The answer by Daniel shows the proper solution and it works just fine in Swift 4.
    – rmaddy
    Oct 11, 2018 at 22:06
-1

Swift 3

   let currentLocale : NSLocale = NSLocale.init(localeIdentifier :  NSLocale.current.identifier)
   let countryName : String? = currentLocale.displayName(forKey: NSLocale.Key.countryCode, value: countryCode)
  print(countryName ?? "Invalid country code")

Note: If you manually entered localIdentifier means iOS 8 not listed all country name (Eg: "en_US")

2
  • 2
    A real Swift 3 answer would use Locale and not NSLocale.
    – Eric Aya
    Mar 1, 2017 at 10:05
  • yes, I agree, But, for IOS 8 am using NSLocale, if you are using Locale means IOS 8 not return proper response. Mar 2, 2017 at 14:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.