What are Lazy Variables and Why Use in Swift

Lazy Variables in Swift

Hello ladies and gentlemen, Leo here. Today the topic is lazy variables and why it’s important for you to know.

The lazy var is a special type of *var* that means the variable value isn’t calculated until we first use it. This brings to the table the flexibility of having 1000 items in memory that may not have all properties set, therefore saving memory space and CPU cycles.

So let’s go to the problem!

 

Problem – Lazy Variables and Why Use in Swift

You have an class/struct that have a property that do some expensive(time wise) work to do, that can be a computed property OR another class or struct that are expensive to call.

I’ll bring here two examples of how you can improve your code using lazy vars. One with a closure call property lazy var and another with a class instantiation.

Both are very important to any iOS developer. Imagine that you have a class that has to set up an object, a view for example, but you only have to instantiate that view in certain conditions, you don’t need to instantiate it if the user will never see it. Lazy variables are here to solve that problem for you.

Let’s check two good implementation examples of lazy variables.

 

The Lazy Closure Variable Example

The first one is using a lazy variable to postpone a closure execution. Check the code below can test with the code above:

print("old index \(fiboManager.fiboIndex)")
print("First fibo value",fiboManager.fibonacciValue)
fiboManager.changeFiboIndex(to: 9)
print("new index \(fiboManager.fiboIndex)")
print("Second fibo value",fiboManager.fibonacciValue)

The result is:

But you are asking why it didn’t change the value after the second call. This is because when you use the closure parameter as above with the lazy in front of it, the compiler delays the calling of the closure until the first time you actually need the value. This is especially good when you have a ton of objects and you don’t need to upfront calculate some of the properties,  you can delay that calculation saving processing time and having a better app experience.

 

The Heavy Class Example

Now, imagine that you have some class that takes time to load. Every time a class needs to use this expensive class, it would take extra time and this isn’t desirable. Would be better only load the expensive class when we actually need it. Check the below example:

class HeavyClassToLoad {
    
    var expensiveVar = "cash.txt"
    
    init() {
        print("Heavy Class initialized")
    }
}

class RandomClassManager {
    lazy var expensiveClass = HeavyClassToLoad()
    var nameList = [String]()
}

As you can see, the manager needs the heavy class at some point, but it doesn’t need it at the time you instantiate the RandomClassManager. If you test the manager:

let manager = RandomClassManager()

manager.nameList.append("Leo")
manager.nameList.append("Ana")

print(manager.nameList)

The result will be only:

 [“Leo”, “Ana”]

But if you try to use the expensiveCiss variable:

manager.expensiveClass.expensiveVar

The result will be as expected:

Only when you first use the expensiveClass variinitializatione manager, it will instantiate it. Remember this when you have some heavy loading class variable that doesn’t need in the moment of the class.

 

Wrap-up – Lazy Variables are you friend

Things to remember:

changed var is always… variables because its initial value might not be retrieved until after instance initialisation is done.
2. If you are using the closure call example, after the first call, itthread-safelculate the value, even if the variables used to calculate de lazy var value had change.
3. The compiler must know beforehand the type of the lazy var, because the actual value is created by evaluation. Or declaring upfront or assigning the direct class.
4. Lazy variables ARE NOT thread safe. This means if multiple threads are trying to access the value of a lazy variable there’s no guarantee that it will be instantiated only once. BE CAREFUL.

 

Summary

Today you learned two really good ways to introduce lazy variables in your Swift codebase. We explained two use cases for your day-to-day development that will help you build faster and more reliable apps.

That’s all my people, I hope you liked reading this article as much as I enjoyed writing it. If you want to support this blog you can Buy Me a Coffee or leave a comment saying hello. You can also sponsor posts and I’m open to freelance writing! You can reach me on LinkedIn or Twitter and send me an e-mail through the contact page.

Thanks for the reading and… That’s all folks.

Credits – image

Share this post:

Related posts

Sponsor