Logo 61e73bc61c0e1780102320e879dc3cac0e29303ea8894dd8f10c942f3ba8120f

otters.io

An adorable little blog

What Does It Mean to Be Lazy?

Monday — April 25th, 2016

Homer

If you’re not a language buff or versed in the dark arts of functional programming then lazy may sound like a strange keyword. How is a feature in a programming language lazy? The obvious answer is a language that doesn’t even try or maybe one that simply opts not to do what you ask.

Lazy loading, as the cool kids call it, is actually a handy way of saying “Don’t prepare this variable until I need it.” You may have seen a similar rendition of this in Objective-C via custom getters and setters. It could look something like this:

@interface Person()
@property NSString *name;
@end

@implementation Person

- (NSString *)name
{
    if (!self.name) {
        self.name = @”Zane”;
    }

    return self.name;
}

@end

When you ask for name, the getter will first check if it has been set yet. If name hasn’t been set, then the getter will go ahead and set it as "Zane" and hand it back to you.

In Swift, the lazy keyword lets us shorten this down tremendously.

class Person {
    lazy var myName = "Zane"
}

Which is especially handy for variables that take a considerable amount of time to set up. If you’ve made a Swift app with CoreData you may have noticed that persistentStoreCoordinator on the boilerplate CoreDataStore is set as lazy. This can help your app start quicker because it only loads up when it's called upon. If you have variables that take a while to set up the first time, you might consider letting them be fashionably late with lazy loading.