Search code examples
objective-cswiftnsmutabledictionarylazy-sequences

What is meaning of NSMutableDictionary.lazy in swift?


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.


Solution

  • 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:

    • Lazy property must always declare with the var keyword, not with the let constant.
    • Lazy properties must be initialized when it is declared.

    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.