I am confused about where to use lazy functionality, I mean to say in which type of condition I should use lazy keyword in the collection.
From Apple Docs:
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.
When use @lazy
property then remembers below things:
var
keyword, not with the let
constant. How we achieve lazy functionality in Objective-C
@property (nonatomic, strong) NSMutableArray *players;
- (NSMutableArray *)players
{
if (!_players) {
_players = [[NSMutableArray alloc] init];
}
return _players;
}
And now in Swift, you can achieve the same functionality by using lazy
property. See below example
class Person {
var name: String
lazy var personalizedGreeting: String = {
return "Hello, \(self.name)!"
}()
init(name: String) {
self.name = name
}
}
Now when you initialize a person, their personal greeting hasn’t been created yet:
let person = Person(name: "John Doe") // person.personalizedGreeting is nil
But when you attempt to print out the personalized greeting, it’s calculated on-the-fly:
print(person.personalizedGreeting)
// personalizedGreeting is calculated when used
// and now contains the value "Hello, John Doe!"
I hope this will help you to understand the functionality of lazy property.