Swift - Lazy Stored Properties

Introduction

You can use the lazy keyword to mark a property as a lazy stored property:


class Point {
   var x = 0.0
   var y = 0.0
   let width = 2
   lazy  var pointMath = PointMath()
}

When the pointMath property is marked as a lazy stored property, it will not be instantiated when the Point is instantiated.

Instead, it will only be instantiated when you access the pointMath property:

print(ptA.pointMath.someValue)

Lazy stored properties must always be declared as a variable using the var keyword and not as a constant using the let keyword.

This is because a lazy stored property's value is not known until it is first accessed.

Related Topic