swift

Lazy property is a property that assumes value only after the class or structure has been initialized. It is defined by adding the word lazy to the word var. The first point to make is that only a variable can be declared lazy, not a constant; this is because the value of the constant has to be known during compilation.

Lazy properties can be useful every time the property value is determined by external factors that may or may not occur, as a result property is created only when it is needed. 

Property observers are functions that are executed when a property varies. These functions are called every time a property is set, even if you do not change the value. The keywords to use are: willSet that is called before the new value is set in the property; didSet called immediately after setting the new value to the property.

class NewRoute {

    var distance: Int = 0 {

        didSet {

            if distance > oldValue {

                print(distance - oldValue)

            }

        }

    }

}

let testRoute = NewRoute()

testRoute.distance = 15 //It is print the value 15

The oldValue parameter is automatically created by the compiler and is the property value before acquiring the new value.

Type properties are "soldered" to the type and can not be modified by instances of the type. It is like defining a static variable in languages like C. The Swift manual provides a very good example; we have a v-meter with two audio channels:

v meter 

This v-meter is represented by two instances of the following structure:

struct AudioChannel {

    static let maxLevel = 10

    static var maxTotalLevel = 0

    

    var currentLevel: Int = 0 {

        

        didSet {

            

            if currentLevel > AudioChannel.maxLevel {

                currentLevel = AudioChannel.maxLevel

            }

            

            if currentLevel > AudioChannel.maxTotalLevel {

                AudioChannel.maxTotalLevel = currentLevel

            }

        }

    }

}

var leftChannel = AudioChannel()

var rightChannel = AudioChannel()

The two channels share the same maximum level and the maximum level reached by one of the two. Although two instances are created, left and right channels, which independently display the respective current signal level, maxLevel and the maxTotalLevel are shared information from both channels, so they are defined as static and are named type property.

Type properties can not be modified by instances of the structure, I can not write:

leftChannel.maxTotalLevel = 5

 

The compiler returns an error indicating that static property can not be modified by an instance. 

Summing up static (or type) properties are useful because they can not be modified by instances so they can convey information between one instance and another.