swiftnslocalecurrency-formatting

How to reduce the amount of currency codes you get back from NSLocale.Key.currencyCode


I have an ios app that I'm trying to allow the users to select which currency they want to use. Right now I have the full list of currencies but there seem to be some duplicates there such as:

enter image description here

Is there a way to filter out the others? The dollar isn't the only one with multiples some have date ranges listed with them.

I'm sure there is some built-in method that does this, but my searching so far hasn't pointed me in the right direction.

Here is what I am doing:

let locale = NSLocale.current as NSLocale
let currencyCodesArray = NSLocale.isoCurrencyCodes
var currencies = [CurrencyModel]()

for currencyCode in currencyCodesArray {
        let currencyName = locale.displayName(forKey:

            NSLocale.Key.currencyCode, value : currencyCode)
        let currencySymbol = locale.displayName(forKey:NSLocale.Key.currencySymbol, value : currencyCode)

        if let _ = currencySymbol, let currencyName = currencyName {
            let currencyModel = CurrencyModel()
            currencyModel.currencyName = currencyName
            currencyModel.currencyCode = currencyCode

            currencies.append(currencyModel)
        }
    }

And then using that data in a talbeView

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell")! as! CurrencyTableViewCell

    cell.name.text = currencies[indexPath.row].currencyName
    cell.symbol.text = currencies[indexPath.row].currencyCode

    return cell
}

And this is my currency model

class CurrencyModel {
var currencyName = ""
var currencyCode = ""

}


Solution

  • You should be using

    Locale.commonISOCurrencyCodes
    

    rather than

    Locale.isoCurrencyCodes