Obj-c code to Swift - NSDateFormatter

574 views Asked by At

I'm trying to create a date formatter that lazy loads and is only initialized once. In Swift, if you create a variable globally, it automatically loads lazilly, so that's taken care of. But how do I only create it once, in a thread-safe manner? I found this obj-c code:

(NSDateFormatter *)formatter {
  static NSDateFormatter *formatter;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    _formatter = [[NSDateFormatter alloc] init];
    _formatter.dateFormat = @"EEE MMM dd HH:mm:ss Z yyyy";
  });
  return formatter;
}

But I'm having trouble re-creating this in Swift, since static variables can only be declared on a type, not a computed property or function. Does this mean I can only re-create this as a class?

EDIT

I know how to create a singleton as a class, I was more wondering if there were a simpler way to use a singleton (global computed property vs class). But on second thought a class is probably better anyway, and its singleton implementation is very simple.

1

There are 1 answers

11
holex On

I guess something similar can do the job for you:

func formatter() -> NSDateFormatter! {
    struct myStatic  {
        static var dateFormatter: NSDateFormatter? = nil
        static var token: dispatch_once_t = 0;
    }
    dispatch_once(&myStatic.token) {
        myStatic.dateFormatter = NSDateFormatter();
        myStatic.dateFormatter?.dateFormat = "EEE MMM dd HH:mm:ss Z yyyy"
    }
    return myStatic.dateFormatter;
}

or alternatively:

lazy var formatter: NSDateFormatter = {
    let dateFormatter: NSDateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "EEE MMM dd HH:mm:ss Z yyyy"
    return dateFormatter
}()