问题
Currently, I have the following code in one of my methods:
let formatter = NSNumberFormatter()
formatter.numberStyle = .DecimalStyle
formatter.currencyGroupingSeparator?
formatter.minimumFractionDigits = 2
Because I have to repeat these in various functions in different view controllers, how do I create a singleton in Swift to call for the NSNumberFormatter and avoid duplicates?
I assume that I have to create a new Swift file, but unsure of how to construct the class?
回答1:
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
回答2:
Ok, what I'd do is make a property that is lazily instantiated. That way you will have no duplicates, and it won't be created and take up memory until you need it.
lazy var numberFormatter = [NSNumberFormatter] = {
var _numberFormatter = [NSNumberFormatter]()
_numberFormatter.numberStyle = .DecimalStyle
_numberFormatter.currencyGroupingSeparator?
_numberFormatter.minimumFractionDigits = 2
return _numberFormatter
}()
回答3:
NSNumberFormatter
isn't that expensive (as compared to NSDateFormatter
) but if you want to have a class method which vends a once only instantiated 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!
}
回答4:
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) ?? ""
}
}
Usage:
Formatters.formatNumber(fromNumber: 100)
When you have a variable with types of Int, CGFloat etc, use:
Formatters.formatNumber(fromNumber: 100 as NSNumber)
来源:https://stackoverflow.com/questions/27571782/singleton-and-nsnumberformatter-in-swift