Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSLocale Swift 3

How do I get the currency symbol in Swift 3?

public class Currency: NSObject {
    public let name: String
    public let code: String
    public var symbol: String {
        return NSLocale.currentLocale().displayNameForKey(NSLocaleCurrencySymbol, value: code) ?? ""
    }

    // MARK: NSObject

    public init(name: String, code: String) {
        self.name = name
        self.code = code
        super.init()
    }
}

I know NSLocale got renamed to Locale, but displayNameForKey got removed and I only seem to be able to use localizedString(forCurrencyCode: self.code) to generate the name of the currency in the current locale without being able to get its symbol. I'm looking for a way to get a foreign currency symbol in a current locale.

Or am I overlooking something?

like image 408
I make my mark Avatar asked Sep 15 '16 19:09

I make my mark


2 Answers

NSLocale was not renamed, it still exists. Locale is a new type introduced in Swift 3 as a value type wrapper (compare SE-0069 Mutability and Foundation Value Types).

Apparently Locale has no displayName(forKey:value:) method, but you can always convert it to its Foundation counterpart NSLocale:

public var symbol: String {
    return (Locale.current as NSLocale).displayName(forKey: .currencySymbol, value: code) ?? ""
}

More examples:

// Dollar symbol in the german locale:
let s1 = (Locale(identifier:"de") as NSLocale).displayName(forKey: .currencySymbol, value: "USD")!
print(s1) // $

// Dollar symbol in the italian locale:
let s2 = (Locale(identifier:"it") as NSLocale).displayName(forKey: .currencySymbol, value: "USD")!
print(s2) // US$
like image 200
Martin R Avatar answered Sep 29 '22 22:09

Martin R


Locale.current.currencySymbol

The new Locale type moved most of the stringly typed properties into real properties. See the developer pages for the full list of properties.

like image 33
keithbhunter Avatar answered Sep 29 '22 22:09

keithbhunter