2016-09-20 188 views
33

请帮助我们了解如何使用NSLocaleSwift 3中获取国家代码?如何在Swift 3中使用NSLocale获取国家代码

这是我以前使用的代码。

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

我可以在斯威夫特3.获得语言代码如下

Locale.current.languageCode! 

正如我所看到的,取语言代码是直线前进,但COUNTRYCODE属性不可用。

+1

在http://stackoverflow.com/a/39519359/1187415中也使用同样的方法:'(Locale.current as NSLocale).object(forKey:.countryCode)'。 –

+0

我可以看到工作。谢谢你的帮助。 – digidhamu

+0

let locale = Locale.current print(locale.regionCode) –

回答

41

参见Wojciech N.'s answer 为更简单的解决方案!


同样为NSLocale Swift 3,你要投的叠加类型Locale回其 基金会对口NSLocale为了获取国家代码:

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

您可以在区域设置使用regionCode属性结构。

Locale.current.regionCode 

它没有被记录为旧的NSLocaleCountryCode结构的替代品,但它看起来像它一样。以下代码检查所有已知语言环境的countryCodes,并将它们与regionCodes进行比较。它们是相同的。如果您尝试使用countryCode与斯威夫特

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

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 
+0

很好地完成了!喜欢它,你基本证明了你的猜想。我知道选择的答案在技术上是正确的,但是哦,我讨厌与NSLocale桥接。 –

-5
print(NSLocale.current.regionCode) 
+0

这与@ wojciech-n从2016年开始的答案是一样的,只是它已经过时了(它应该是Swift 3中的Locale,而不是Swift 2中的NSLocale)。 – Moritz

0

如果你确保你使用的是NSLocale,而不是一个Locale例如,你可以使用countryCode属性Locale Xcode会给你一个错误,建议使用regionCode来代替:

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