swift - Swift 中的惰性属性初始化

标签 swift

您将如何在 Swift 中实现以下模式?

Container 类使用包含字典的 JSON 数组进行初始化。这些字典用于初始化 Entry 类。但是,当访问 entriessearchEntries 属性时,Entry 对象的初始化会延迟进行。

@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

最佳答案

这个怎么样:

class Container {

    lazy var entries: [String] = self.newEntries()

    func newEntries() -> [String] {

        // calculate and return entries

    }

}

关于swift - Swift 中的惰性属性初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24107938/

相关文章:

swift - 插入图像后 NSTextView 未更新

ios - 使用 Swift 查询可用的 iOS 磁盘空间

swift - NSTimer 在触发后挂起程序

ios - 将类型别名作为类类型存储在 NSHashTable 中

ios - GameCenter - 在调用处理程序之前检查以前的登录?

swift - 自定义 UIView 作为背景

ios - WatchOS3中SKShapeNode添加手势

ios - 如何使用@available 定位低于特定操作系统的 iOS 设备

swift - ReloadData不刷新列表

ios - Xcode - 链接器命令失败,退出代码为 1