Skip to content

Instantly share code, notes, and snippets.

@mattt
Last active December 19, 2023 19:21
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mattt/6d022b66f08ea8c1b99ebe7e48b95c4b to your computer and use it in GitHub Desktop.
Save mattt/6d022b66f08ea8c1b99ebe7e48b95c4b to your computer and use it in GitHub Desktop.
import Foundation
extension Locale {
func localizedCurrencySymbol(forCurrencyCode currencyCode: String) -> String? {
guard let languageCode = languageCode, let regionCode = regionCode else { return nil }
/*
Each currency can have a symbol ($, £, ¥),
but those symbols may be shared with other currencies.
For example, in Canadian and American locales,
the $ symbol on its own implicitly represents CAD and USD, respectively.
Including the language and region here ensures that
USD is represented as $ in America and US$ in Canada.
*/
let components: [String: String] = [
NSLocale.Key.languageCode.rawValue: languageCode,
NSLocale.Key.countryCode.rawValue: regionCode,
NSLocale.Key.currencyCode.rawValue: currencyCode,
]
let identifier = Locale.identifier(fromComponents: components)
return Locale(identifier: identifier).currencySymbol
}
}
Locale.isoCurrencyCodes.compactMap { (code) -> String? in
guard let name = Locale.current.localizedString(forCurrencyCode: code),
let symbol = Locale.current.localizedCurrencySymbol(forCurrencyCode: code)
else {
return nil
}
return "\(name) - \(symbol) (\(code))"
}
@Tulakshana
Copy link

Tulakshana commented Aug 19, 2021

Never mind I figured it out.

import Foundation

func listCountriesAndCurrencies() {
    let localeIds = Locale.availableIdentifiers
    var countryCurrency = [String: String]()
    for localeId in localeIds {
        let locale = Locale(identifier: localeId)

        if let country = locale.regionCode {
            if let currency = locale.currencySymbol {
                countryCurrency[country] = currency
            }
        }
    }

    let sorted = countryCurrency.keys.sorted()
    for country in sorted {
        let currency = countryCurrency[country]!

        print("country: \(country), currency: \(currency)")
    }
}

listCountriesAndCurrencies()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment