How to get country code using NSLocale in Swift 3

微笑、不失礼 提交于 2019-12-17 22:22:02

问题


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.


回答1:


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



回答2:


You can use regionCode property on Locale struct.

Locale.current.regionCode

It is not documented as a substitute for old NSLocaleCountryCode construct but it looks like it is. The following code checks countryCodes for all known locales and compares them with regionCodes. They are identical.

public func ==(lhs: [String?], rhs: [String?]) -> Bool {
    guard lhs.count == rhs.count else { return false }

    for (left, right) in zip(lhs, rhs) {
        if left != right {
            return false
        }
    }

    return true
}

let newIdentifiers = Locale.availableIdentifiers
let newLocales = newIdentifiers.map { Locale(identifier: $0) }
let newCountryCodes = newLocales.map { $0.regionCode }

let oldIdentifiers = NSLocale.availableLocaleIdentifiers
newIdentifiers == oldIdentifiers // true

let oldLocales = oldIdentifiers.map { NSLocale(localeIdentifier: $0) }
let oldLocalesConverted = oldLocales.map { $0 as Locale }
newLocales == oldLocalesConverted // true

let oldComponents = oldIdentifiers.map { NSLocale.components(fromLocaleIdentifier: $0) }
let oldCountryCodes = oldComponents.map { $0[NSLocale.Key.countryCode.rawValue] }
newCountryCodes == oldCountryCodes // true



回答3:


If you make sure that you're using an NSLocale and not a Locale instance, you can use the countryCode property:

let locale: NSLocale = NSLocale.current as NSLocale
let country: String? = locale.countryCode
print(country ?? "no country")
// > Prints "IE" or some other country code

If you try to use countryCode with a Swift Locale Xcode will give you an error with a suggestion to use regionCode instead:

let swiftLocale: Locale = Locale.current
let swiftCountry: String? = swiftLocale.countryCode
// > Error "countryCode' is unavailable: use regionCode instead"



回答4:


print(NSLocale.current.regionCode)


来源:https://stackoverflow.com/questions/39596238/how-to-get-country-code-using-nslocale-in-swift-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!