Swift - Class Lazy properties


You can create a property lazy.

A lazy property doesn't get set up until the first time it's accessed.

You can defer some of the time-consuming work of setting up a class to when it's actually needed.

To define a property as lazy, put the lazy keyword in front of it.

Lazy loading is useful for properties that are not essential to the class.


class MyClass { 
    init(id  : Int) { 
        print("Expensive class \(id) created!") 
    } //from www  .  ja v a 2s. c  o m

class Car { 
    var my1 = MyClass(id: 1) 
    lazy var my2 = MyClass(id: 2) 
    init() { 
        print("Example class created!") 

var lazyExample = Car() 
print(lazyExample.my1 )
print(lazyExample.my2 )


Here, when the lazyExample variable is created, it immediately creates the first instance of MyClass.

However, the second instance, my2, isn't created until it's actually accessed by the code.

Lazy properties can only be declared as mutable variables; you can't have a lazy let variable in your code.

Related Topic