Wednesday, April 29, 2015

Lazy Loading in Swift


Lazy loading is a technique to initialize the property only if they are called. In this way, memory is not allocated  to the property until it’s not initialized and if this property is not used then memory will never be allocated to this property. Lazy loading is also known as Dynamic loading.

In Swift, we have the keyword lazy to initialize the property with lazy loading. Lazy keyword makes sure that the property will be initialized only when its gets called and it would be initialized only once.

Also, whenever we want to declare the lazy property, always use the var keyword not let keyword as constant must always have a value before the initialization.

Here, we have define the Person Class with two properties name and message with lazy attribute means this variable will be initialized only when it is used. 

class Person {
    
    var name : String?
    lazy var message: String = {
        return "Hello \(self.name!)"
        }()
    
    init(name: String) {
        self.name = name
    }
}

Now, initialize the Person class. This will also initiate the name property but message is not initialized means person.mesage is nil.

var person = Person(name: "John"



And when you tries to use the message properties then it will initialized.

println("\(person.message)") //  Hello John
      
As the message property closure will be called only once so even if you update the name property, it will not make any changes to your message property.
  
person.name = "Jimmy"
println("\(person.message)") //  Hello John


Lazy loading technique is used to improve the performance and to perform expensive operation. Swift has provided the direct support for lazy initialization with lazy attribute.