我有货币代码(例如:“UAH”)。在我的代码中,我得到货币符号相等的货币代码(“UAH”),但是对于“USD”和“EUR” - “$”和“€”。为什么呢?
let currencyCode = "UAH"
let localeComponents = [NSLocaleCurrencyCode: currencyCode]
let localeIdentifier = NSLocale.localeIdentifierFromComponents(localeComponents)
let locale = NSLocale(localeIdentifier: localeIdentifier)
let currencySymbol = locale.objectForKey(NSLocaleCurrencySymbol)
我找到了解决方案:
let locales: NSArray = NSLocale.availableLocaleIdentifiers()
for localeID in locales as! [NSString] {
let locale = NSLocale(localeIdentifier: localeID as String)
let code = locale.objectForKey(NSLocaleCurrencyCode) as? String
if code == "UAH" {
let symbol = locale.objectForKey(NSLocaleCurrencySymbol) as? String
print(symbol!)
break
}
}
答案 0 :(得分:4)
因为您的locale
设置不正确。除了货币代码之外,系统对您的区域设置一无所知。有两十个左右的区域设置,其中USD
为货币代码;其货币符号在US$
和$
之间变化。 UAH
有两种可用的区域设置:ru_UA
和uk_UA
。
更安全的方法是迭代所有与您指定的货币代码相同的区域设置,然后使用规则从结果列表中选择:
let currencyCode = "UAH"
let currencySymbols = NSLocale
.availableLocaleIdentifiers()
.map { NSLocale(localeIdentifier: $0) }
.filter {
if let localeCurrencyCode = $0.objectForKey(NSLocaleCurrencyCode) as? String {
return localeCurrencyCode == currencyCode
} else {
return false
}
}
.map {
($0.localeIdentifier, $0.objectForKey(NSLocaleCurrencySymbol)!)
}
print(currencySymbols) // Now you can choose from the list