22: Swift. Class and Lazy Property

Lazy property is a special type of property whose initial value will be calculated when it will be called.

Create a class Person with two normal properties name and age and one lazy property mywebsite by adding lazy keyword at front.

class Person {
    // properties
    var name : String = "Khan"
    var age  : Int = 30
    lazy var mywebsite = "www.understand-programming.com"

Now all variables of this class are assigned with values, name = Khan and age = 30 and mywebsite is assigned with string. Create an object of person class

var p = Person()

and observe the output in console:

{name “Khan” age 30 nil}.

First variable name contains “Khan”, Second variable age has value 30 and last lazy variable is nil. Now remove the lazy keyword from class and observe the output again:

{name “Khan” age 30 mywebsite “www.understand-programming.com”}

As soon as you removed the lazy keyword, the lazy property became a normal property which shows that if propery is lazy it is not initialized automatically. Now put the lazy keyword back and you will notice this output again {name “Khan” age 30 nil}.

Call this lazy mywebsite variable with person object.


Now variable is initialized with website address.


Continue with Class and Protocol…


Download file from GitHub