Singleton and NSNumberFormatter in Swift

I currently have the following code in one of my methods:

let formatter = NSNumberFormatter()
formatter.numberStyle = .DecimalStyle
formatter.currencyGroupingSeparator?
formatter.minimumFractionDigits = 2

      

Since I have to repeat them in different functions in different view managers, how do I create a singleton in Swift to call NSNumberFormatter and avoid duplicates?

I'm guessing I need to create a new Swift file, but don't know how to build the class?

+3


source to share


4 answers


update: Xcode 8.2.1 • Swift 3.0.2



extension Double {
    static let twoFractionDigits: NumberFormatter = {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        formatter.minimumFractionDigits = 2
        formatter.maximumFractionDigits = 2
        return formatter
    }()
    var formatted: String {
        return Double.twoFractionDigits.string(for: self) ?? ""
    }
}

100.954345.formatted    // 100.95

      

+4


source


Ok, I would make this property lazy created. This way, you won't have duplicates and it won't be created and will take up memory until you need it.



lazy var numberFormatter = [NSNumberFormatter] = {
    var _numberFormatter = [NSNumberFormatter]()
    _numberFormatter.numberStyle = .DecimalStyle
    _numberFormatter.currencyGroupingSeparator?
    _numberFormatter.minimumFractionDigits = 2
    return _numberFormatter
}()

      

0


source


NSNumberFormatter

not that expensive (compared to NSDateFormatter

), but if you want to have a class method that vends only one instance of an object

class var prettyFormatter:NSNumberFormatter {

        struct SingletonNumberFormatter {
            static var instance:NSNumberFormatter?
        }

        if SingletonNumberFormatter.instance == nil {
            SingletonNumberFormatter.instance = NSNumberFormatter()
            SingletonNumberFormatter.instance.numberStyle = .DecimalStyle
            SingletonNumberFormatter.instance.currencyGroupingSeparator?
            SingletonNumberFormatter.instance.minimumFractionDigits = 2
        }

        return SingletonNumberFormatter.instance!
 }

      

0


source


Another Singleton solution:

class Formatters{
    static let twoFractionDigits: NumberFormatter = {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        formatter.minimumFractionDigits = 2
        formatter.maximumFractionDigits = 2
        return formatter
    }()
    static func formatNumber(fromNumber: NSNumber) -> String{
        return twoFractionDigits.string(from: fromNumber) ?? ""
    }
}

      

Using:

Formatters.formatNumber(fromNumber: 100)

      

If you have a variable with types Int, CGFloat, etc., use:

Formatters.formatNumber(fromNumber: 100 as NSNumber)

      

0


source







All Articles