如何通过CurrencyCode获取CountryCode?技术实现咨询
通过CurrencyCode获取CountryCode的解决方案
首先得指出你当前代码里的问题:NSLocale(localeIdentifier: "CNY") 是错误的用法,因为localeIdentifier需要的是区域标识符(比如zh_CN、en_US),而不是货币代码。所以这样创建的Locale对象根本无法正确关联到对应的国家信息,自然拿不到正确的CountryCode。
接下来回到你的核心需求:不依赖当前设备的Locale,通过货币代码反向查找对应的国家代码。这里要先明确一个关键点:一种货币可能对应多个国家/地区(比如USD对应美国、厄瓜多尔、巴拿马等),所以无法做到严格的一对一映射,通常需要返回一个包含所有对应国家代码的数组。
具体实现代码(Swift)
下面是一个可以实现这个功能的函数,它会遍历所有可用的Locale,筛选出使用目标货币代码的Locale,然后提取对应的区域代码(CountryCode):
func getCountryCodes(for currencyCode: String) -> [String] { var matchingCountryCodes = Set<String>() // 获取系统所有可用的Locale标识符 let allLocales = Locale.availableIdentifiers for localeId in allLocales { let locale = Locale(identifier: localeId) // 检查当前Locale的货币代码是否匹配目标 if let localeCurrency = locale.currencyCode, localeCurrency == currencyCode { // 提取对应的区域代码(CountryCode) if let countryCode = locale.regionCode { matchingCountryCodes.insert(countryCode) } } } // 转成数组返回(去重后) return Array(matchingCountryCodes) } // 使用示例:获取CNY对应的国家代码 let cnyRelatedCountries = getCountryCodes(for: "CNY") print(cnyRelatedCountries) // 输出 ["CN"] // 再比如获取USD对应的国家代码 let usdRelatedCountries = getCountryCodes(for: "USD") print(usdRelatedCountries) // 会包含US、PA、EC等多个国家代码
补充说明
- 用
Set来存储国家代码是为了自动去重,因为不同的Locale(比如en_US和es_US)可能对应同一个国家代码。 - 如果你的需求只需要最常用的那个国家代码,可以对返回的数组做额外处理(比如取第一个元素,或者根据优先级筛选)。
- 这种方式不需要依赖当前设备的Locale,完全基于系统内置的Locale数据来查找,符合你“货币与位置无关”的要求。
内容的提问来源于stack exchange,提问作者Koh
相关产品推荐
相关产品推荐

