相关疑难解决方法(0)

懒惰加载属性在swift中

我试图围绕Swift语言.使用Objective-C在代码中构建视图时的常见模式是覆盖UI属性并延迟加载它们,如下所示:

@property(nonatomic, strong) UILabel *myLabel;

- (UILabel *)myLabel
{
     if (!_myLabel) {
         _myLabel = [[UILabel alloc] initWithFrame:CGRectMake(20.0f, 75.0f, 320.0f, 20.0f)];
        [_myLabel setFont:[UIFont subHeadlineFont]];
        [_myLabel setTextColor:[UIColor subHeadlineColor]];
        [_myLabel setText:@"Hello World"];
     }
     return _myLabel;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.view addSubview:self.myLabel];
}
Run Code Online (Sandbox Code Playgroud)

这允许UIElements的配置在其设置中自包含,但不会导致每次重新配置它们.

我们似乎无法访问Swift中的后备存储,并且@lazy关键字实际上没有相同的语义.

我很好奇是否有人在Swift中发现了一个类似的模式,它允许人们以一种整洁的语法方式将变量和常量的配置与它们的声明一起保存,每次都不会导致重新配置?

swift

37
推荐指数
2
解决办法
2万
查看次数

标签 统计

swift ×1