【问题标题】:How to get Country Code from Country Name Using Swift? [duplicate]如何使用 Swift 从国家名称中获取国家代码? [复制]
【发布时间】:2019-05-21 22:01:31
【问题描述】:

我的场景,我试图通过使用国家名称来获取国家代码。我尝试了下面的代码,但它只获取国家名称。

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

【问题讨论】:

  • 您的代码从国家代码中获取国家名称,而不是您声称的相反,当我测试它时它工作正常。请澄清您的要求。
  • stackoverflow.com/a/48790731 能解决您的问题吗?
  • @MartinR 我试过了,但它只适用于苹果支持的国家。我需要获得所有国家/地区。
  • @jackios:除非我弄错了,否则“南非荷兰语”是一种语言而不是一个国家/地区。
  • @MartinR okey 尝试“南非”

标签: swift


【解决方案1】:
if let countryCode = (Locale.current as NSLocale).object(forKey: .countryCode) as? String {
   return countryCode
}

【讨论】:

  • 你可以在一行中完成return ((Locale.current as NSLocale).object(forKey: .countryCode) as? String) ?? countryCode
  • 如果他们解释问题和解决方案,而不是只发布代码,答案会更有帮助。
猜你喜欢
  • 2016-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-28
  • 2020-09-13
  • 2016-11-27
  • 1970-01-01
相关资源
最近更新 更多