Get currency symbols from currency code with swift

前端 未结 11 677
星月不相逢
星月不相逢 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 13:08

    A bit late but this is a solution I used to get the $ instead of US$ etc. for currency symbol.

    /*
     * Bear in mind not every currency have a corresponding symbol. 
     *
     * EXAMPLE TABLE
     *
     * currency code | Country & Currency | Currency Symbol
     *
     *      BGN      |   Bulgarian lev    |      лв   
     *      HRK      |   Croatian Kuna    |      kn
     *      CZK      |   Czech  Koruna    |      Kč
     *      EUR      |       EU Euro      |      €
     *      USD      |     US Dollar      |      $
     *      GBP      |   British Pound    |      £
     */
    
    func getSymbol(forCurrencyCode code: String) -> String? {
       let locale = NSLocale(localeIdentifier: code)
       return locale.displayNameForKey(NSLocaleCurrencySymbol, value: code)
    }
    

    Basically this creates NSLocale from your currency code and grabs the display attribute for the currency. In cases where the result matches the currency code for example SEK it will create new country specific locale by removing the last character from the currency code and appending "_en" to form SE_en. Then it will try to get the currency symbol again.

    Swift 3 & 4

    func getSymbol(forCurrencyCode code: String) -> String? {
        let locale = NSLocale(localeIdentifier: code)
        if locale.displayName(forKey: .currencySymbol, value: code) == code {
            let newlocale = NSLocale(localeIdentifier: code.dropLast() + "_en")
            return newlocale.displayName(forKey: .currencySymbol, value: code)
        }
        return locale.displayName(forKey: .currencySymbol, value: code)
    }
    

提交回复
热议问题