swiftlocalecurrencycountry-codes

How do I find the Locale Identifier using the ISO country code (2 letters)


In my App I would like to display the correct currency code depending on the country the user is looking in:

var isoCountryCode = "GB"
    
let currency = Locale(identifier: isoCountryCode).currency?.identifier ?? "GBP"

So instead of hard coding "GB" I would like to replace this with a variable that uses the ISOCountryCode to determine the Locale Identifier. i.e. for the United Kingdom this would be GB as the two character ISO country code and the result would either be "en_GB".

Alternatively, if there is an easier way to use the Country Code to determine the local currency, I would be equally happy.


Solution

  • I have found the answer here:

    swift get currencycode from country code

    The code was a bit outdated, so the updated code is:

    let components: [String: String] = [NSLocale.Key.countryCode.rawValue: isoCountryCode]
        
    let identifier = NSLocale.localeIdentifier(fromComponents: components)
        
    let locale = NSLocale(localeIdentifier: identifier)
        
    let currencyCode = locale.object(forKey: NSLocale.Key.currencyCode)