swift - 如何使用 Swift 从国家名称中获取国家代码?
问题描述
我的场景,我试图通过使用国家名称来获取国家代码。我尝试了下面的代码,但它只获取国家名称。
func countryName(from countryCode: String) -> String {
if let name = (Locale.current as NSLocale).displayName(forKey: .countryCode, value: countryCode) {
// Country name was found
return name
} else {
// Country name cannot be found
return countryCode
}
}
解决方案
if let countryCode = (Locale.current as NSLocale).object(forKey: .countryCode) as? String {
return countryCode
}
推荐阅读
- angular - Angular - 下拉验证 - 在 mouseup 事件之前显示验证
- visual-studio-code - 使用多个容器设置 Visual Studio Code
- c# - 获取 EventHandler 以在原始线程上调用 Invoke()
- javascript - TypeError:无法读取未定义的属性“长度” - Firebase
- python - 为什么我们不能为调度方法表中的函数添加括号 - Python?
- c++ - 如何通过 HTTP 将 RapidJSON::Document 作为 json 而不是字符串发送?
- ios - 反应原生 PIP
- linux - 如何配置路由以允许流量在具有私有地址的以太网设备和公共地址之间传递,Linux
- python - 想在相同的比赛后打印额外的字符,在这种情况下只有“s”
- azure - 通过 HAproxy 到 Azure iothub 的 Azure SDK python 客户端(SSL 握手失败)