Formatters
2 min 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:
struct Utils {
class var numberFormatter: NumberFormatter {
struct Static {
static let formatter = NumberFormatter()
}
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
print(x.maximumFractionDigits) // => 3
print(x.alwaysShowsDecimalSeparator) // => trueBut throughout the app the "default" settings will be returned:
let y = Utils.numberFormatter
print(y.maximumFractionDigits) // => 2
print(y.alwaysShowsDecimalSeparator) // => falseJust 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
print(x.maximumFractionDigits) // => 2
print(x.alwaysShowsDecimalSeparator) // => false