Thursday 17 November 2016

Lazy Stored Property In Swift3.0

Today we learn about lazy stored property in swift.What is lazy stored property and how it works?We also know about its advantage .Lets start with its implementation. 

Lazy Stored Property :
A lazy stored property is a property whose initial value is not calculated until the first time it is used.You indicate a lazy stored property by writing the lazy modifier before its declaration.

Note*You must always declare a lazy property as a variable (with the var keyword), because its initial value might not be retrieved until after instance initialization completes. Constant properties must always have a value before initialization completes, and therefore cannot be declared as lazy.

class Number {
  lazy var value =87
    
  func showNumber() {
    print("My luck number is \(value)")
  }
  
}
let number = Number()
print(number.showNumber())


Here Sample class having lazy stored property named "no".Here instance of Number class is declared as lazy stored property.The lazy keyword makes sure the property is only set if / when showNumber function  it’s called. 

In Swift, you can use a closure  to set the value in  lazy stored property

class Number {
  lazy var value: Int = {
    return 87
  }()
  func showNumber() {
    print("My luck number is \(value)")
  }
  
}
let number = Number()
print(number.showNumber())

Advantage of using lazy stored property:
  1. Lazy properties are useful when the initial value for a property is dependent on outside factors whose values are not known until after an instance’s initialization is complete.
  2. Lazy properties are also useful when the initial value for a property requires complex or computationally expensive setup that should not be performed unless or until it is needed.
  3. Lazy loading is initializing your properties only if / when they are called. This way, memory is not allocated for that property until absolutely necessary, and if the property is actually never used, the memory doesn’t get allocated at all.

Conclusion : Today we studied about lazy stored property in swift. If  you guys any query or concern you can leave your comment.I will  try to reply your query as soon as possible.

No comments:

Post a Comment