Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setup for a date formatter (for example) at initialization time?

Tags:

swift

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.)

like image 895
Fattie Avatar asked Jul 19 '26 04:07

Fattie


2 Answers

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.

like image 137
vadian Avatar answered Jul 21 '26 19:07

vadian


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")
like image 41
Ivan Avatar answered Jul 21 '26 21:07

Ivan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!