Swift Tutorial - Tutorialspoint

(backadmin) #1

Lazy Stored Property


Swift provides a flexible property called 'Lazy Stored Property' where it won't calculate the
initial values when the variable is initialized for the first time. 'lazy' modifier is used before
the variable declaration to have it as a lazy stored property.


Lazy Properties are used:


 To delay object creation.

 When the property is dependent on other parts of a class, that are not known yet

class sample {
lazy var no = number() // `var` declaration is required.
}

class number {
var name = "Swift"
}

var firstsample = sample()
println(firstsample.no.name)

When we run the above program using playground, we get the following result:


Swift

Instance Variables


In Objective C, Stored properties also have instance variables for back up purposes to
store the values declared in stored property.


Swift integrates both these concepts into a single 'stored property' declaration. Instead of
having a corresponding instance variable and back up value 'stored property' contains all
integrated information defined in a single location about the variables property by variable
name, data type and memory management functionalities.


Computed Properties


Rather than storing the values computed properties provide a getter and an optional setter
to retrieve and set other properties and values indirectly.


class sample {
var no1 = 0.0, no2 = 0.0
var length = 300.0, breadth = 150.0
Free download pdf