您将如何在 Swift 中实现以下模式?
Container
类使用包含字典的 JSON 数组进行初始化。这些字典用于初始化 Entry
类。但是,当访问 entries
或 searchEntries
属性时,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/