Skip to content

Instantly share code, notes, and snippets.

@hishma
Last active December 11, 2020 06:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hishma/180fa4e7839fee1dca6fc72540556471 to your computer and use it in GitHub Desktop.
Save hishma/180fa4e7839fee1dca6fc72540556471 to your computer and use it in GitHub Desktop.
/// The Locale for a currency code.
///
/// The returned Locale may only contain currency information.
///
/// - Parameter currencyCode: An ISO currency code. See `Locale.commonISOCurrencyCodes` for a list of supported currency codes.
/// - Returns: The Locale corresponding to the currency code, or nil if its not a vakid currency code.
static func localeFrom(currencyCode: String) -> Locale? {
// Make sure the currency code is supported
guard self.commonISOCurrencyCodes.contains(currencyCode) else { return nil }
// If this is the same currency code as the users current locale, return the current locale since
// it is more complete and will allow our currency formatter to correctly display the correct
// optional currency symbol as appropriate (E.G. '$' instead of 'US$'.
guard Locale.current.currencyCode != currencyCode else { return Locale.current }
let localeComponents = [NSLocale.Key.currencyCode.rawValue: currencyCode]
let localeIdentifier = Locale.identifier(fromComponents: localeComponents)
return Locale(identifier: localeIdentifier)
}
@Mattiav8
Copy link

If anyone need to use this code on Linux (my app was crushing because NSLocale), the localeComponent constant can be initialize like this:
let localeComponents = Locale.identifier(fromComponents: ["currency": "(currencyCode)"])
return Locale(identifier: localeIdentifier.uppercased())

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