Lazy Properties in Swift

Lately, a reviewer comment about lazy properties drew my attention. So i decided to do a quick guide on the go to get people started with lazy properties. What is a lazy property ? How and when should you use it?

What is a lazy Stored Property ?

A lazy stored property is a property that should not be initialized until is first accessed.

Why would you want to use a lazy property ?

Lazy property is often used when the initial value is relatively expensive to create. For example, if we have a view controller that displays a GPSCar, we might want to have a preview image of the car. By prefixing the property with lazy keyword, we can defer the expensive generation of the image until the property is accessed for the first time:

class GPSCarViewController: UIViewController {
var car: GPSCar = GPSCar()

lazy var preview: UIImage = {
// Do some expensive work
return UIImage()
}()
}

How To: Lazy property In Swift

The easiest way to define a lazy property, is to simply prefix the var with lazy (You can’t make it lazy let because lazy property must always be variable) :

class Person {
lazy var name: String = "John"
}

However, sometimes the initial value is computationally intensive. A closure is the way to go :

class Person {
lazy var age: Int = {
return // do some of your magic
}()

}

The advantage of this approach is that you can keep both the property declaration and its setup in one place.

Points to remember :

  1. The lazy property is calculated only once when initialized.
  2. The closure associated to the lazy property is executed only if you read that property.
  3. You can use self inside the closure of a lazy property.