Source: abhimuralidharan.medium.com/lazy-var-in…

In iOS app development, you need to pay special attention to the memory of the application. If the app is designed to be complex, then memory issues can become a major problem. So developers need to avoid doing a lot of unnecessary work.

Swift has a mechanism built into the language to do instant calculations for expensive work, called lazy variables. This change is created only when it is needed. If it is not necessary, for example, the function will never be executed, then the lazy variable will never be created.

Here’s Apple’s official explanation:

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

The lazy storage variable has the following advantages over the storage variable:

  1. Inside the closurelazyProperties are only executed when you read them. This way you can avoid unnecessary memory allocation and computation if the familiarity is not used (e.g. by user choice);
  2. You can copy a storage property tolazyattribute
  3. You can pass it in a closureselfTo access thelazyProperties. This does not cause circular references. The reason for this is that there is an attachment after the closure{} ()You can view this as@noescape.
class InterviewTest {
    var name: String
    lazy var greeting: String = {return "Hello \ [self.name)"} ()// no retain cycles here....
    
    init(name:String) {
        self.name = name
    }
}

let testObj = InterviewTest(name: "abhi")
testObj.greeting // Hello abhi
Copy the code

Lazy Rules

  • uselazyCannot be used whenlet
  • You cannot modify computed attributes. Because, each time a computed property is accessed, the code returns.
  • lazyCan only be modifiedstructandclassA member of the
  • lazyThe variable is not atomic when initialized, so it is not thread-safe