I\'m a beginner and I sort of understand Lazy Var vs. Let. I\'ve noticed that it saves a ton of memory usage when using Lazy Var especially with ImageViews. But the tutorials an
Another advantage to using a lazy var
is improving the readability of your code.
In your example, the code related to the image view is grouped together instead of being spread out to an initializer, setup function, or viewDidLoad
. This improves local reasoning by not requiring the reader of the code to venture to various places in the code to understand how your view is configured. To learn about your view, they only need to jump to its declaration.
An initialization closure marked as a lazy var
can access self
, allowing for more configuration to be done inside the closure, such as adding target actions or referencing other constant properties.
I would consider initializing properties (especially views) with closures as lazy var
's to be a good practice, and it seems to be gaining popularity in the Swift community as well.
Depending on the project, saving developer time can be much more valuable than saving system memory.