Formatters

:  ~ 45 sec read

Since creating formatters is very expensive, it's a good idea to have a singleton for them. But what if you have a standard style throughout the app, except a couple of places? Encapsulate it in a Static struct and set the required settings before returning:

class var numberFormatter: NSNumberFormatter {
  struct Static {
    static let formatter = NSNumberFormatter()
  }
	
  Static.formatter.maximumFractionDigits = 2
  Static.formatter.alwaysShowsDecimalSeparator = false
		
  return Static.formatter
}

Then in the places with a different style:

let x = Utils.numberFormatter
x.maximumFractionDigits = 3
x.alwaysShowsDecimalSeparator = true
println(x.maximumFractionDigits) // => 3
println(x.alwaysShowsDecimalSeparator) // => true

But throughout the app the "default" settings will be returned:

let y = Utils.numberFormatter
println(y.maximumFractionDigits) // => 2
println(y.alwaysShowsDecimalSeparator) // => false

Just be careful with this approach - if you allocate y between allocating and using x, you will get the default settings for both x and y:

let x = Utils.numberFormatter
x.maximumFractionDigits = 3
x.alwaysShowsDecimalSeparator = true

let y = Utils.numberFormatter

println(x.maximumFractionDigits) // => 2
println(x.alwaysShowsDecimalSeparator) // => false