从国家/地区代码获取国家/地区名称

从国家/地区代码获取国家/地区名称

问题描述:

我已经找到了针对Objective-C的答案,但林先生很难迅速做到这一点.

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

但是如何将这个国家/地区代码转换为国家/地区名称,例如在此示例中,将"US"转换为"United States"?

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

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
    }
}