Last active
December 11, 2020 06:05
-
-
Save hishma/180fa4e7839fee1dca6fc72540556471 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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())