Lazy property initialization in Swift

后端 未结 9 1124
深忆病人
深忆病人 2020-12-18 04:25

How would you implement the following pattern in Swift?

The Container class is initialized with a JSON array that contains dictionaries. These dictionar

9条回答
  •  离开以前
    2020-12-18 04:46

    The way lazy works is that the initializer (or init method) runs only when the variable or property is first accessed. I see one main reason why it won't work (at least straight away) in your code, and that is because you packed two lazy instantiation code into one method (loadEntriesIfNeeded).

    To use lazy instantiation, you might need to extend NSMutableArray and NSDictionary and override or create a custom initializer for your lazy instantiation. Then, distribute the code inside loadEntriesIfNeeded into their respective initializers.

    In entries initializer:

    NSMutableArray *entries = [NSMutableArray arrayWithCapacity:[self.entriesDict count]];
    [self.entriesDict enumerateKeysAndObjectsUsingBlock:^(NSString *number, NSDictionary *entryDict, BOOL *stop) {
                Entry *entry = [[Entry alloc] initWithDictionary:entryDict container:self];
                [entries addObject:entry];}];
    _entries = [entries copy];
    

    Then in entriesByNumber initializer:

    NSMutableDictionary *entriesByNumber = [NSMutableDictionary dictionaryWithCapacity:[self.entriesDict count]];
    // Then do fast enumeration accessing self.entries to assign values to entriesByNumber.
    // If self.entries is null, the lazy instantiation should kick in, calling the above code
    // and populating the entries variable.
    _entriesByNumber = [entriesByNumber copy];
    

    Then, you can create your lazy variables by calling on the custom initializers.

    @lazy var entries: CustomArray = custominitforarray()
    @lazy var entriesByNumber: CustomDictionary = custominitfordictionary()
    

    PS: How come you don't have a property for entriesByNumber? I'm guessing it's private? Please test this out and reply about the result as I'm too lazy to do it myself.

提交回复
热议问题