I have successfully been able to create a singleton object in Swift, but I feel that the implementation is rather verbose. Is there a way to shorten this code up? And combine multiple formatters into one class where each formatter is its own singleton?
import Foundation
class sharedNumberFormatterWithOneDecimalPlace : NSNumberFormatter {
class var sharedInstance: sharedNumberFormatterWithOneDecimalPlace {
struct Singleton {
static let instance = sharedNumberFormatterWithOneDecimalPlace()
}
return Singleton.instance
}
override init () {
super.init()
self.minimumIntegerDigits = 1
self.maximumFractionDigits = 1
self.minimumFractionDigits = 1
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
In my other class I can call it by:
NSNumberFormatter *formatter = sharedNumberFormatterWithOneDecimalPlace.sharedInstance;
NSLog(@"%@", [formatter stringFromNumber:aNumber]);
I would like to be able to have 1 class of "MultipleFormatters" where I set up many formatters that get used all over the place, and then call something like "MultipleFormatters.OneDecimalPlace" for example.
PS. I have already read post: Using a dispatch_once singleton model in Swift
Thanks.