How would you implement the following pattern in Swift?
The Container class is initialized with a JSON array that contains dictionaries. These dictionaries are used to initialize Entry classes. However, the initialization of the Entry objects happens lazily, when either the entries or the searchEntries property is accessed.
@interface Container
@property (readonly, nonatomic) NSArray *entryDicts;
@property (readonly, nonatomic) NSArray* entries;
@property (readonly, nonatomic) NSDictionary *searchEntries;
@end
@implementation Container
- (instancetype)initWithArray:(NSArray *)array
{
self = [super init];
if (self) {
_entryDicts = array;
}
return self;
}
@synthesize entries = _entries;
- (NSArray *)entries
{
[self loadEntriesIfNeeded];
return _entries;
}
@synthesize entriesByNumber = _entriesByNumber;
- (NSDictionary *)entriesByNumber
{
[self loadEntriesIfNeeded];
return _entriesByNumber;
}
- (void)loadEntriesIfNeeded
{
if (_entries == nil) {
// Load entries
NSMutableArray *entries = [NSMutableArray arrayWithCapacity:[self.entriesDict count]];
NSMutableDictionary *entriesByNumber = [NSMutableDictionary dictionaryWithCapacity:[self.entriesDict count]];
[self.entriesDict enumerateKeysAndObjectsUsingBlock:^(NSString *number, NSDictionary *entryDict, BOOL *stop) {
Entry *entry = [[Entry alloc] initWithDictionary:entryDict container:self];
[entries addObject:entry];
entriesByNumber[number] = entry;
}];
_entries = [entries copy];
_entriesByNumber = [entriesByNumber copy];
// Delete dictionaries
_entriesDict = nil;
}
}
@end