Search code examples
swiftswift3number-formattingcurrency-formattingnumberformatter

Using the Same Currency Formatting in Multiple Methods


I'm using some currency formatting to set currency symbols/styles to the user's local settings. Here is my code. I think it works fine. It is located in my viewDidLoad.

let currencyFormat = NumberFormatter()    
currencyFormat.locale = NSLocale.current
currencyFormat.usesGroupingSeparator = true
currencyFormat.numberStyle = NumberFormatter.Style.currency
...
labelTotalAmount.text = currencyFormat.string(for: totalAmount)

The trouble is, I want to use this same formatting in two other different Methods. It seems to be a waste to repeat the formatting for each method whenever I want to do formatting.

Is there a way to set the formatting once and have it remember the settings in every method of the class?

I'm using Swift 3. I appreciate any help you can give!!


Solution

  • Make it a computed property of the class:

    class Whatever {
        let currencyFormat: NumberFormatter = {
            let res = NumberFormatter()
            res.numberStyle = .currency
            res.usesGroupingSeparator = true
            return res
        }()
    }
    

    Now you can use that property in any method.

    func someMethod() {
        let str = currencyFormat.string(for: 5.99)
    }