Topics

#302: Lazy Properties 🐤💤

Topics

Today we're going to begin looking at the lazy keyword in Swift. It describes some functionality in the language for what Apple calls " just-in-time calculation" of work.

This is great for times when we have expensive work to perform, or maybe the work is just some ugly complex code we'd like to tuck away. Perhaps we simply want to better compartmentalize the bits of our code that initialize UI elements, the use cases are plenty.

Today we'll start with Lazy Variables. Let's dive in!

Say we have a View Controller with a titleLabel. Pretty old school standard stuff.

We need to create the titleLabel, save it to a property, configure some stuff about it, then add it into the view heirarchy.

We want this work to be done after the view is loaded, and not when the view controller is first created, so we are forced to put it in viewDidLoad.

Additionally, we're forced to use a UILabel! force-unwrapped type on our titleLabel property to make the compiler happy.

It ends up looking something like this:

class ViewController: UIViewController {
  var titleLabel : UILabel!

  override func viewDidLoad() {
    super.viewDidLoad()

    titleLabel = UILabel()

    titleLabel.font = UIFont(name: "Source Sans Pro", size: 18.0)
    titleLabel.textColor = UIColor.brown

    view.addSubview(titleLabel)
  }

Let's make our titleLabel lazy and clean this junk up:

class ViewController: UIViewController {
  lazy var titleLabel : UILabel = {
    let label = UILabel()

    label.font = UIFont(name: "Source Sans Pro", size: 18.0)
    label.textColor = UIColor.brown

    return label
  }()

  override func viewDidLoad() {
    super.viewDidLoad()

    view.addSubview(titleLabel)
  }
}

Neat!

We've now dramatically improved our viewDidLoad implementation. Cool.

We've also neatly compartmentalized the bit of code that sets up that label. Cool cool.

Perhaps most importantly though, we've now better expressed our intentions using language keywords (and their resulting behaviors), Cool cool cool.

Note: We have to use var instead of let when defining lazy properties like this. Our property might not (likely won't) have an initial value until after the instance of our view controller is created and its view is loaded. This completely breaks the rules of lets (constants).

That's all for now, in future Bites we'll look at other lazy behaviors in Swift!