首页 > 解决方案 > 如何使用 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
    }
}

标签: swift

解决方案


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

推荐阅读