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.
I guess something similar can do the job for you:
or alternatively: