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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With