问题描述
您能否帮助我了解如何在 Swift 3
中使用 NSLocale
获取国家/地区代码?
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
我可以在 Swift 3 中获得如下语言代码.
I can get Language Code as below in Swift 3.
Locale.current.languageCode!
如我所见,获取 languageCode 很简单,但 countryCode 属性不可用.
As I can see, fetching languageCode is straight forward but countryCode property is not available.
推荐答案
参见 Wojciech N. 的回答寻求更简单的解决方案!
See Wojciech N.'s answerfor a simpler solution!
与NSLocale Swift 3类似,您必须转换覆盖类型Locale
回到它的基础对应 NSLocale
以检索国家/地区代码:
Similarly as in NSLocale Swift 3, you have to cast the overlay type Locale
back to itsFoundation counterpart NSLocale
in order to retrieve the country code:
if let countryCode = (Locale.current as NSLocale).object(forKey: .countryCode) as? String {
print(countryCode)
}
这篇关于如何在 Swift 3 中使用 NSLocale 获取国家代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!