Say you have a date formatter that is global
let df:DateFormatter = DateFormatter()
Ideally it would be good to do the .dateFormat setup at the same global initialization time - sort of like this
let df:DateFormatter = DateFormatter().dateFormat = "yyyy-MM-dd"
But there's no alternative initialization for DateFormatter (there's nothing like this DateFormatter(withDateFormat: "yyyy-MM-dd") )
Really, is there a Swift solution to this? Is there syntax for a code block outside of any class, which, runs early before anything and in which you can setup things of that nature?
(Note - I am entirely aware of alternative approaches such as singletons, extension, etc: this is a Swift structure question, thanks.)
Use a closure to make your settings
let df : DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
return formatter
}()
However you are discouraged from using uncapsulated global variables.
You are free to implement a convenience initializer in an extension, like this:
extension DateFormatter {
convenience init(dateFormat: String) {
self.init()
self.dateFormat = dateFormat
}
}
Usage:
let dateFormatter = DateFormatter(dateFormat: "yyyy-MM-dd")
dateFormatter.date(from: "2017-02-22")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With