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

Tar*_*erw 10 location swift

我找到了针对Objective-c的答案,但我很难在swift中做到这一点.

我用它来获取当前位置的国家/地区代码:

     let countryCode = NSLocale.currentLocale().objectForKey(NSLocaleCountryCode) as! String
    print(countryCode)
// printing for example US
Run Code Online (Sandbox Code Playgroud)

但是,如何将此国家/地区代码转换为国家/地区名称,例如将"美国"转换为"美国"?

AlB*_*ebe 25

斯威夫特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
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @RobertGummesson 见丹尼尔的回答。 (2认同)

Dan*_*iel 21

超级干净的Swift 3版本将是:

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

您可以将区域设置标识符更改为例如.如果您想要本地化名称,请使用Locale.current.identifier.以上示例仅适用于英语.


Mic*_*ann 8

尝试做这样的事情:

// 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)")
}
Run Code Online (Sandbox Code Playgroud)

我在这里找到了这个辅助函数:

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)
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我通过研究这个相关的问题来解决这个问题.


lor*_*nzo 6

这是一个紧凑的swift 4版本,一直为我工作:

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

或者像 @Memon 这样的优雅扩展建议:

extension Locale {

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

}
Run Code Online (Sandbox Code Playgroud)