0

I'm using an extension to NSDate:

extension NSDate {
    func toDayMonthYear() -> String {
        let formatter = NSDateFormatter()
        formatter.dateFormat = "dd.MM.yy"
        return formatter.stringFromDate(self)
    }
}

This way I can easily turn any values to NSDate

print(NSDate().toDayMonthYear)   => "12.11.2015"

But I understand that each and every time this gets called, an instance of NSDateFormatter is created which is - performancewise - catastrofic...

How can I do that more elegantly?

Timm Kent
  • 1,123
  • 11
  • 25
  • how often is called toDayMonthYear() ? For usual usage it seems fine – nsinvocation Nov 12 '15 at 20:46
  • See http://stackoverflow.com/questions/28504589/whats-the-best-practice-for-nsdateformatter-in-swift. – Martin R Nov 12 '15 at 20:47
  • It is used very often. That's why I'm worried about performance. And it's not quite as easy as Martin R says, because I'm within an extension. I want this independantly from any other classes. – Timm Kent Nov 12 '15 at 20:49

1 Answers1

2

You can define a static property (which is assigned only once) locally in functions or (extension) methods, but you need to embed it in a structure:

extension NSDate {

    func toDayMonthYear() -> String {

        struct Statics {
            static var formatter : NSDateFormatter = {
                let fmt = NSDateFormatter()
                fmt.dateFormat = "dd.MM.yy"
                return fmt
            }()
        }

        return Statics.formatter.stringFromDate(self)
    }
}
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382