trw trw - 3 months ago 38
Swift Question

Getting country name from country code

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"?

Answer

Try doing something like this:

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

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

var theEnglishName : String? = englishLocale.displayNameForKey(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.

Comments