Get currency symbols from currency code with swift

前端 未结 11 629
星月不相逢
星月不相逢 2020-12-24 12:21

How can I get the currency symbols for the corresponding currency code with Swift (macOS).

Example:

  • EUR = €1.00
  • USD = $1.00<
11条回答
  •  粉色の甜心
    2020-12-24 12:52

    An imperfect solution I found to get $ instead of US$ or CA$ was to attempt to match the user's current locale to the currency code first. This will work for situations where you're building a mobile app and an API is sending you currency code based on the settings in that user's account. For us the business case is that 99% of users have the same currency code set in their account on the backend (USD, CAD, EUR, etc.), where we're getting the information from, as they do on their mobile app where we're displaying currency the way a user would expect to see it (i.e. $50.56 instead of US$ 50.56).

    Objective-C

    - (NSLocale *)localeFromCurrencyCode:(NSString *)currencyCode {
        NSLocale *locale = [NSLocale currentLocale];
        if (![locale.currencyCode isEqualToString:currencyCode]) {
            NSDictionary *localeInfo = @{NSLocaleCurrencyCode:currencyCode};
            locale = [[NSLocale alloc] initWithLocaleIdentifier:[NSLocale localeIdentifierFromComponents:localeInfo]];
        }
        return locale;
    }
    

    Swift

    func locale(from currencyCode: String) -> Locale {
        var locale = Locale.current
        if (locale.currencyCode != currencyCode) {
            let identifier = NSLocale.localeIdentifier(fromComponents: [NSLocale.Key.currencyCode.rawValue: currencyCode])
            locale = NSLocale(localeIdentifier: identifier) as Locale
        }
        return locale;
    }
    

提交回复
热议问题