0

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!!

Jupiter869
  • 657
  • 2
  • 7
  • 19

1 Answers1

1

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)
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • I'm not sure why this is not working for me. Perhaps I am putting the 'Whatever' class in the wrong spot? I've located it both outside my class Viewcontroller: UIViewController and inside. – Jupiter869 Mar 23 '17 at 20:21
  • That's meant to be whatever your class is. Don't create a new class. Just make `currencyFormat` a property of your view controller class (or whatever class needs this property). – rmaddy Mar 23 '17 at 20:22
  • Thank you for correcting my stupid mistake! Now it works wonderfully! Thanks!!! – Jupiter869 Mar 23 '17 at 20:29