Home > Software design >  How to get the currency symbol from Locale Swift
How to get the currency symbol from Locale Swift

Time:08-20

Trying to make a computed property that show all possible currencies to be shown on a UIPickerView. Currently, the symbols I get in my array always is ¤ any tips to make it work?

import UIKit

struct MyCurrency: Codable {
    let code: String
    let name: String
    let symbol: String
}

var currencies: [MyCurrency] {
    return Locale.Currency.isoCurrencies.compactMap {
        guard let name = Locale.current.localizedString(forCurrencyCode: $0.identifier),
              let symbol = Locale(identifier: $0.identifier).currencySymbol  else { return nil }
        return MyCurrency(code: $0.identifier, name: name, symbol: symbol)
    }
}

print(currencies)

CodePudding user response:

You need to iterate through the locales, and get currency code with this you can get all the rest

var currencies: [MyCurrency] {
    return Locale.availableIdentifiers.compactMap {
        guard let currencyCode = Locale(identifier: $0).currencyCode,
              let name = Locale.autoupdatingCurrent.localizedString(forCurrencyCode: currencyCode),
              let symbol = Locale(identifier: $0).currencySymbol  else { return nil }
        return MyCurrency(code: $0, name: name, symbol: symbol)
    }
}

enter image description here

  • Related