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:
- Inside the closure
lazy
Properties 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); - You can copy a storage property to
lazy
attribute - You can pass it in a closure
self
To access thelazy
Properties. 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
- use
lazy
Cannot be used whenlet
- You cannot modify computed attributes. Because, each time a computed property is accessed, the code returns.
lazy
Can only be modifiedstruct
andclass
A member of thelazy
The variable is not atomic when initialized, so it is not thread-safe