我已經成功地在Swift中創建了一個單身人士對象,但我覺得這個實現比較冗長。有沒有辦法縮短這個代碼?並將多個格式化程序組合成一個類,其中每個格式化程序都是它自己的單例程?在Swift中創建單身人士
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")
}
}
在我的其他類我可以調用它:
NSNumberFormatter *formatter = sharedNumberFormatterWithOneDecimalPlace.sharedInstance;
NSLog(@"%@", [formatter stringFromNumber:aNumber]);
我希望能有1類「MultipleFormatters」在那裏我設置一個習慣遍佈許多格式化放置,然後調用諸如「MultipleFormatters.OneDecimalPlace」之類的東西。 PS。我已閱讀帖子:Using a dispatch_once singleton model in Swift
謝謝。
[在迅速調度\ _once單模型(http://stackoverflow.com/questions/24024549/dispatch-once-singleton-model-in-swift) – Shmidt 2014-08-27 13:29:29