如何在 Swift 3 中使用 NSLocale 获取国家代码 [英] How to get country code using NSLocale in Swift 3

查看:26
本文介绍了如何在 Swift 3 中使用 NSLocale 获取国家代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您能否帮助我了解如何在 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 answer for a simpler solution!

NSLocale Swift 3类似,您必须转换覆盖类型Locale 回到它的基础对应 NSLocale 以检索国家/地区代码:

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

这篇关于如何在 Swift 3 中使用 NSLocale 获取国家代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆