Get currency symbols from currency code with swift

前端 未结 11 620
星月不相逢
星月不相逢 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:14

    The proper way to do this is to let the frameworks provide the information for you.

    You can retrieve that information using an obscure class method on NSLocale called localeIdentifierFromComponents(). That method will take a dictionary that defines various attributes of your locale, and then returns an identifier you can use to actually construct an NSLocale instance. Once you have the NSLocale, you can ask it for its CurrencySymbol, like this:

    let currencyCode = "CAD"
    
    let localeComponents = [NSLocaleCurrencyCode: currencyCode]
    let localeIdentifier = NSLocale.localeIdentifierFromComponents(localeComponents)
    let locale = NSLocale(localeIdentifier: localeIdentifier)
    let currencySymbol = locale.objectForKey(NSLocaleCurrencySymbol) as! String
    // currencySymbol is "CA$"
    

提交回复
热议问题