How to get currency symbol from currency code for all available places in Swift?

I have a currency code (for example: "UAH"). In my code, I get a currency symbol equal to the currency code ("UAH"), but for "USD" and "EUR" - "$" and "€". Why?

let currencyCode = "UAH"

let localeComponents = [NSLocaleCurrencyCode: currencyCode]

let localeIdentifier = NSLocale.localeIdentifierFromComponents(localeComponents)

let locale = NSLocale(localeIdentifier: localeIdentifier)

let currencySymbol = locale.objectForKey(NSLocaleCurrencySymbol)

I found a solution:

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
    }
}
+4
source share
1 answer

Because yours localewas set up incorrectly. The system does not know anything about your locale other than the currency code. There are two dozen or so places with USDas a currency code; their currency symbols vary between US$and $. UAHhas 2 locales available: ru_UAand 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
+3

Source: https://habr.com/ru/post/1619363/


All Articles