Mikhail Tseitlin
Mikhail Tseitlin

Reputation: 109

How to rename the currency code to the full name of the currency? Swift

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

Upvotes: 0

Views: 879

Answers (2)

SGDev
SGDev

Reputation: 2252

Use Locale instead of NSLocale

  func getCurrencyFullName(code: String) -> String? {
        let locale1 = Locale(identifier: code)
        return locale1.localizedString(forCurrencyCode: code)
    }

it is help you.

Upvotes: 1

rmaddy
rmaddy

Reputation: 318774

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 "українська гривня".

Upvotes: 2

Related Questions