如何在 Swift 3 中创建缓存的 NSNumberFormatter?

How to create a cached NSNumberFormatter in Swift 3?

我想知道如何在 Swift 3 中创建缓存的 NSNumberFormatter (NumberFormatter)?

这是我通过搜索要点找到的;

extension NumberFormatter {
    private static var cache:[String:NumberFormatter] = [:]

    static func numberFormatterForKey(key:String, initialize:((NumberFormatter)->())? = nil) -> NumberFormatter {
        if let formatter = NumberFormatter.cache[key] {
            return formatter
        } else {
            let formatter = NumberFormatter()
            NumberFormatter.cache[key] = formatter
            initialize?(formatter)
            return formatter
        }
    }
}

但是我不知道怎么用;或者有更好的解决办法。

因此,如何在 Swift 3 中创建缓存的 NSNumberFormatter?

我已经解决了这个问题;

我这样创建缓存的 nsnumberformatter;

struct ObjectCache {
    static let currencyRateFormatter: NumberFormatter = {
        var numberFormatter = NumberFormatter()
        numberFormatter.locale = Locale(identifier: "en_US")
        numberFormatter.numberStyle = .currency
        numberFormatter.minimumFractionDigits = 0
        numberFormatter.maximumFractionDigits = 0
        numberFormatter.alwaysShowsDecimalSeparator = false
        return numberFormatter
    }()
}

那就这样用吧;

self.myCashLbl.text = ObjectCache.currencyRateFormatter.string(from: NSNumber(integerLiteral: player.cash))

谢谢。