Keyword Lazy in Swift

· 1 min read
Keyword Lazy in Swift

lazy variables are variables will be computed until accessing. In other words, lazy variables won't have the real value until get called/used. As lazy variables can be re-assigned, so it can't be used on constants which normally defined by let.

One example of using lazy variables:

class MyClass {
    
    lazy var names: NSArray = {
        let names = NSArray()
        print("Only run at the first time access")
        return names
    }()
    
}

let myClass = MyClass()
myClass.names    // Only run at the first time access
myClass.names    // NO OUTPUT

Scenarios of use

One of the good use scenarios is we can use the lazy feature on View initialization setup. For example, if the view have multiple states, such as empty list or populated list, they can be lazily loaded when in different situation, so the compiler won't have to compute both of the two views (empty and populated) at one time.

What about Objective-C

Objective-C doesn't natively support the lazy, but some simple workout can be easily implemented.


@interface ViewController ()

@property (nonatomic) float value;

@end

@implementation ViewController

- (float)value {
    if (!_value) {
        _value = 0.0f;
        NSLog(@"Only run at the first time access");
    }
    return _value;
}

Reference