如何在Swift 3中使用NSLocale获取国家代码

你可以请帮忙在Swift 3使用NSLocale获取国家代码吗?

这是我以前使用的代码。

 NSLocale.currentLocale().objectForKey(NSLocaleCountryCode) as! String 

我可以在Swift 3中获得如下语言代码。

 Locale.current.languageCode! 

正如我所看到的,获取languageCode是直接的,但countryCode属性不可用。

请参阅Wojciech N.的答案,以获得更简单的解决scheme!


与NSLocale Swift 3类似,您必须将覆盖typesLocale重新转换回其基础对应NSLocale ,以检索国家/地区代码:

 if let countryCode = (Locale.current as NSLocale).object(forKey: .countryCode) as? String { print(countryCode) } 

你可以在Locale结构体上使用regionCode属性。

 Locale.current.regionCode 

它没有被logging为旧的NSLocaleCountryCode结构的替代品,但它看起来是这样的。 以下代码检查所有已知语言环境的countryCodes,并将其与regionCodes进行比较。 他们是相同的。

 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 
 print(NSLocale.current.regionCode)