Brent Westmoreland Brent Westmoreland - 1 month ago 11
Swift Question

Lazy loading Properties in swift

I'm attempting to wrap my head around the Swift language. A common pattern when building views in code with Objective-C is to override UI properties and lazy load them like so:

@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];
}


This allows for the configuration of UIElements to be self contained within their setup but doesn't result in reconfiguring them every time.

It seems we don't have access to the backing store in Swift and the
@lazy
keyword doesn't really have the same semantics.

I'm curious if anyone has identified a similar pattern in Swift that allows one to keep the configuration of variables and constants together with their declaration in a neat syntactic way that doesn't result in reconfiguration every time?

Answer

I think a lazy property initialized with a closure would work:

lazy var myLabel: UILabel = {
    var temporaryLabel: UILabel = UILabel()
    ...
    return temporaryLabel
}()

As I read “The Swift Programming Language.” (Checkerboard example) the closure is only evaluated once).