What Are Lazy Variables
Variables can be lazy
to save processing time of your running code. A lazy variable is created only when it is called upon.
Example
Here is a struct called Person, that has an age
variable, as well as a fibonacciOfAge
variable. Also, Person()
has a function that calculates
the fibonacci of a given integer. The function uses recursion, and it gets exponentially complex the higher the input.
struct Person {
var age = 16
lazy var fibonacciOfAge: Int = {
return fibonacci(of: self.age)
}()
func fibonacci(of num: Int) -> Int {
if num < 2 {
return num
} else {
return fibonacci(of: num - 1) + fibonacci(of: num - 2)
}
}
}
In this situation, making fibonacciOfAge a lazy variable could save a tremendous amount of processing time, if you don’t need the fibonnacci age to be computed by default.
By making it lazy, fibonacciOfAge will only be computed when it gets called. Imagine if you create 100 instances of Person()
, then you would definitely
need to use lazy.
Notes about the example code
- You must declare the variable's data type (
Int
in the example). - Must use
.self
inside the function. If using class instead of struct, use[unowned self]
to avoid strong reference cycle. - Lazy property must end with parenthesis (You are making a call to the function you just created.)
- There is no
lazy let
, only variables.
Written on November 16, 2020