1

I'm trying to put together a utility class that converts to/from ISO8601 representations. So far, I've got the following:

import Foundation

class ISODateConversion {
    static let WithMilliseconds = NSDateFormatter()
    static let SansMilliseconds = NSDateFormatter()

    class func dateFromString(input:String) -> NSDate  {
        return WithMilliseconds.dateFromString(input) ?? SansMilliseconds.dateFromString(input)
    }

    class func stringFromDate(date:NSDate) ->String {
        return SansMilliseconds.stringFromDate(date)
    }
}

But I need to more than just instantiate those two formatters. I want them to be initialized with the following expressions:

WithMilliseconds.timeZone = NSTimeZone(abbreviation: "GMT")
WithMilliseconds.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.S"

SansMilliseconds.timeZone = NSTimeZone(abbreviation: "GMT")
SansMilliseconds.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"

NSDateFormatter doesn't have an in init() that allows me set those at creation time. But I only need them to be created once and then just reused. What's the right pattern/way to do this.

(I also think that I should change this to be extensions to String and NSDate, but I still have the issue of how I have my module do a one time setup of these reusable formatters).

Travis Griggs
  • 21,522
  • 19
  • 91
  • 167

1 Answers1

3

Use a define-and-call anonymous function as your initializer:

static let WithMilliseconds : NSDateFormatter = {
    let d = NSDateFormatter()
    d.timeZone = NSTimeZone(abbreviation: "GMT")
    d.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.S"
    return d
}()
matt
  • 515,959
  • 87
  • 875
  • 1,141
  • And see my book: http://www.apeth.com/swiftBook/ch02.html#SECdefineandcall and http://www.apeth.com/swiftBook/ch03.html#_computed_initializer – matt Apr 28 '15 at 17:36
  • Chuckle, last time you answered one of my questions, I bought your Programming iOS7 book per your suggestion. It was a real help. This time, I beat you to it. I bought your book yesterday (it's on its way). So I bought the book *before* you helped me this time. :) – Travis Griggs Apr 28 '15 at 18:42
  • By the way, I can't believe how useful this define-and-call idiom is in Swift. I use it all the time. It figures heavily in this answer I just gave yesterday: http://stackoverflow.com/a/29908825/341994 And it is the basis of this trick for defining an arbitrary local scope: http://stackoverflow.com/a/28177504/341994 – matt Apr 28 '15 at 19:05