I created this method. I have an array of currency code. But when I insert a code, for example: “USD”, the method returns me Optional (“US dollar”). And whenever I try to extract an option, I get a nil. What did I do wrong?
func getCurrencyFullName(code: String) -> String? {
let locale = NSLocale(localeIdentifier: code)
print(locale.displayName(forKey: NSLocale.Key.countryCode, value: code) // Optional "US dollar"
return locale.displayName(forKey: NSLocale.Key.countryCode, value: code)
}
let dollar = getCurrencyFullName(code: UAH)
print(dollar) // nil
Your primary issue is that you are trying to create a locale from a currency code and then you try to use that invalid locale to translate the currency code into a name. Just use the user's current locale to convert the currency code.
You should also use Locale
instead of NSLocale
.
func getCurrencyFullName(code: String) -> String? {
return Locale.current.localizedString(forCurrencyCode: code)
}
In an English locale, this gives "Ukrainian Hryvnia" for UAH. In a Ukrainian locale, this gives "українська гривня".