David Yang

Tips and posts for iOS developers from an iOS developer.

Lazy properties is a very simple concept, that many may know without even knowing it. It allows us to declare properties which will only be created when needed.

The following Objective-C code sample may look familiar and simpler to understand.

@interface MyClass: NSObject

@property (nonatomic, strong) NSDateFormatter *apiDateFormatter;

@end

@implementation MyClass

- (NSDateFormatter *)apiDateFormatter {
    if (_apiDateFormatter == nil) {
        _apiDateFormatter = [NSDateFormatter new];
        _apiDateFormatter.dateFormat = @"yyy-MM-dd";
    }
    return _apiDateFormatter;
}

@end

Here, the apiDateFormatter method acts as the property’s getter and returns our NSDateFormatter instance. But it will only create our NSDateFormatter once, when it is read for the first time.

Future calls to the getter will then just return the instance that has already been created.

This mechanism can be useful when working with an object that may take time to create. It can optimize an app’s performance.

In Swift, this concept is handled by a simple keyboard : lazy.

Here is the Swift version :

class MyClass {
    lazy var apiDateFormatter: DateFormatter = makeApiDateFormatter()
    
    private func makeApiDateFormatter() -> DateFormatter {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyy-MM-dd"
        return formatter
    }
}

Or alternatively, with a self-executing closure:

class MyClass {
    lazy var apiDateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyy-MM-dd"
        return formatter
    }()
}

Conclusion

We now have a “lazy” apiDateFormatter property: you may now call apiDateFormatter a hundred times, its creation will only occurs once.