title: Lazy property initialization in Swift
body: <p>How would you implement the following pattern in Swift?</p>
  
  <p>The <code>Container</code> class is initialized with a JSON array that contains dictionaries. These dictionaries are used to initialize <code>Entry</code> classes. However, the initialization of the <code>Entry</code> objects happens lazily, when either the <code>entries</code> or the <code>searchEntries</code> property is accessed.</p>
  
  <pre><code>@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
  </code></pre>