Gaurav Borole
Gaurav Borole

Reputation: 846

Swift: Get currency symbol from currency code is not working

I want Currency symbol from Currency code. for e.g) EUR -> €, USD -> $, SEK -> kr, DKK -> kr

I am using below code to get currency symbol.

func getSymbolForCurrencyCode(code: String) -> String? {
   let locale = NSLocale(localeIdentifier: code)
   return locale.displayName(forKey: NSLocale.Key.currencySymbol, value: code)
}

But it returns SEK for SEK and DKK for DKK, it should return kr. For USD, GBP, EUR its working fine.

What could be the issue?

Upvotes: 2

Views: 5057

Answers (2)

93sauu
93sauu

Reputation: 4097

I have created two extensions for strings adding cache to optimize the search.

extension String {
    private static let currencyCode = NSCache<NSString, NSString>()

    public var symbolForCurrencyCode: String? {
        if let cached = Self.currencyCode.object(forKey: self as NSString) {
            return cached as String
        }
        let identifiers = Locale.availableIdentifiers
        guard let identifier = identifiers.first(where: { Locale(identifier: $0).currencyCode == self }) else {
            return nil
        }

        guard let symbol = Locale(identifier: identifier).currencySymbol else {
            return nil
        }

        Self.currencyCode.setObject(symbol as NSString, forKey: self as NSString)

        return symbol
    }
}

extension Optional where Wrapped == String {
    public var symbolForCurrencyCode: String? {
        guard let code = self else {
            return nil
        }
        return code.symbolForCurrencyCode
    }
}

"GBP".symbolForCurrencyCode // "£"
"EUR".symbolForCurrencyCode // "€"
"SEK".symbolForCurrencyCode // "kr"

Upvotes: 2

Vlad Khambir
Vlad Khambir

Reputation: 4383

It works without using NSLocale class (Swift 3/4):

func getSymbolForCurrencyCode(code: String) -> String? {
    let result = Locale.availableIdentifiers.map { Locale(identifier: $0) }.first { $0.currencyCode == code }
    return result?.currencySymbol
}
getSymbolForCurrencyCode(code: "GBP")

Upvotes: 5

Related Questions