Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring and initializing static objects at class scope

Tags:

swift

In Objective-C, it is common for a class to keep a static reference to an instance that the class will use several times. For example,

@implementation MyClass

static NSDateFormatter *dateFormatter = nil;

+ (void) initialize {
    if (self == [MyClass class]) {
        dateFormatter = [[NSDateFormatter alloc] init];
    }
}

@end

In Swift we no longer have to declare and initialize this static object in two different places. We can simply do

let dateFormatter = NSDateFormatter()

at class scope and the date formatter is initialized when the class is loaded.

My question: when writing in Swift, is there any reason not to use this new pattern? It would still be possible to declare the date formatter at module scope and then initialize it within initialize; is there any reason to do it in two steps like this?

like image 631
bdesham Avatar asked Oct 21 '22 07:10

bdesham


1 Answers

No, there's no such reason; the self-initializing variable is the way to go.

Even better, self-initialize it to a called closure and the date formatter can be further initialized / configured, right there.

Not only that, but if you mark it as @lazy then it won't even be initialized until the first time you actually access it.

like image 176
matt Avatar answered Oct 27 '22 10:10

matt