Learning Swift: Being Lazy with Lazy Instantiation


swift-logo-hero.jpgswift-logo-hero.jpg

Lazy loading, or what is also referred to as Lazy Initialization is the process of delaying the instantiation of an object, deferring it until needed. Working with limited or scarce memory resources, it can be helpful to sometimes only take what you need (or in this case use what you need when you need it).

A lazy stored property is a property whose initial value is not calculated until the first time it is used. You indicate a lazy stored property by writing the lazy modifier before its declaration.

— Apple Swift Documentation (http://goo.gl/FHpjMq)

The usefulness of this is apparent when you are in a situation where your variable value cannot be assigned immediately, but is rather dependent on ‘outside factors’ where the values won’t e known until a dependent initialization is completed. Having complex or computational properties are expensive and deferring initialization is a way of optimizing memory usage, accordingly. 

Mike Buss conveniently illustrates how this was done in Objective-c:

@property (nonatomic, strong) NSMutableArray *players;

- (NSMutableArray *)players {
if (!_players) {
_players = [[NSMutableArray alloc] init];
}
return _players;
}

Fast-forward to the future and Swift, and we can do the same, simply as follows:

lazy var players = [String]()

Marking the variable with the lazy modifier means the property is only created when the players is first accessed. This is a great example of being explicitly efficient. 

 

Leave a Reply

Your email address will not be published. Required fields are marked *