2

I have an extension set up on String to return the current date in the same format so that anywhere in code it can be called and the same format is used, allowing for consistency. My code is

extension String {
    static let dateString = DateFormatter.localizedString(from: Date(), dateStyle: .short, timeStyle: .short)
}

The only problem is that when I call it the same exact time is returned until the app is killed. If I'm using Date() then it should be using a fresh value every time, right? Why is this not the case?

Cody Harness
  • 1,116
  • 3
  • 18
  • 37

1 Answers1

6

A (static) stored property is initialized exactly once (on first access). Compare Properties in “The Swift Programming Language”:

Stored type properties are lazily initialized on their first access. They are guaranteed to be initialized only once, even when accessed by multiple threads simultaneously, and they do not need to be marked with the lazy modifier.

What you want is a computed property:

extension String {
    static var dateString: String {
        return DateFormatter.localizedString(from: Date(), dateStyle: .short, timeStyle: .short)
    }
}

Remark: As Leo Dabus says, it makes more sense as an instance property of Date. Here is an example taken from NSDate() or Date() shows the wrong time:

extension Date {
    func localString(dateStyle: DateFormatter.Style = .medium, timeStyle: DateFormatter.Style = .medium) -> String {
        return DateFormatter.localizedString(from: self, dateStyle: dateStyle, timeStyle: timeStyle)
    }
}
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • 2
    IMO String should be omitted from the property name and it would make more sense as an instance property extension on `Date`. – Leo Dabus Sep 26 '18 at 14:02