1

I am having some confusion in lazy stored property. I read many tutorials and found this, but I could not understand this in real scenario. Can anyone please clear out few things,

  1. A lazy stored property is a property whose initial value is not calculated until the first time it is used...

  2. You must always declare a lazy property as a variable (with the var keyword), because its initial value may not be retrieved until after instance initialization completes...

  3. 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.

  4. Where should we use lazy stored property

Thanks

1
  • 2
    What is the issue you are facing with lazy stored properties? These statements are very clear in their meaning. Commented May 29, 2017 at 10:29

2 Answers 2

4

Mike Buss wrote an article about lazy initialization in Swift http://mikebuss.com/2014/06/22/lazy-initialization-swift/

One example of when to use lazy initialization is when the initial value for a property is not known until after the object is initialized or when the computation of the property is computationally expensive.

Here are two examples for both cases from the post:

In the first example we don't know which value personalized greeting should have. We need to wait until the object is initialized to know the correct greeting for this person.

class Person {

var name: String

lazy var personalizedGreeting: String = {
    [unowned self] in
    return "Hello, \(self.name)!"
    }()

init(name: String) {
        self.name = name
    }
}

The second example covers the case of an expensive computation. Imagine a MathHelper class which should give you values for pi and other important constants. You don't need to calculate all constants if you only use a subset of them.

class MathHelper {

lazy var pi: Double = {
    // Calculate pi to a crazy number of digits
    return resultOfCalculation
    }()

}
Sign up to request clarification or add additional context in comments.

2 Comments

How to change personalizedGreeting If I change name?? In same code..
You may want to take a look at this question. You have multiple ways to trigger a reinitialization of your lazy attributes.
4

Explained well!! I want to add a simple example to understand it in a better way.

Lazy property is a stored property whose memory will be allocated only when the variable is actually used.

class Car{
    lazy var brand: String = "BMW" // Memory not allocated
}

let aCar = Car()
print(aCar.brand) // Memory allocated as it is getting used here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.