dispatch_once in Swift : a 24 hours journey

func formatSomeStuff() {
struct Static {
static var onceToken: dispatch_once_t = 0
static var numberFormatter: NSNumberFormatter? = nil
}
dispatch_once(&Static.onceToken) {
Static.numberFormatter = NSNumberFormatter()
if let numberFormatter = Static.numberFormatter {
numberFormatter.numberStyle = NSNumberFormatterStyle.PercentStyle
numberFormatter.maximumFractionDigits = 1
}
}
//Do stuff
}
class MyClass {
lazy var numberFormatter: NSNumberFormatter = {
let numberFormatter = NSNumberFormatter()
numberFormatter.numberStyle = NSNumberFormatterStyle.PercentStyle
numberFormatter.maximumFractionDigits = 1
return numberFormatter
}()
func formatStuff() {
//Do stuf with (self.)numberFormatter
}
}
class MyClass {
static let numberFormatter: NSNumberFormatter = {
let numberFormatter = NSNumberFormatter()
numberFormatter.numberStyle = NSNumberFormatterStyle.PercentStyle
numberFormatter.maximumFractionDigits = 1
return numberFormatter
}()
func formatStuff() {
//Do stuf with (self.)numberFormatter
}
}

--

--

--

Software Engineer (iOS) @producteev / @jivesoftware

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jerome

Jerome

Software Engineer (iOS) @producteev / @jivesoftware

More from Medium

How capture lists work and how their behaviour differ for value and reference types in Swift

Is Swift the Objective Choice now?

[Swift] Struct vs Class

UserDefaults Unit testing in iOS