Swift - Lazy Var vs. Let when creating views programmatically (saving memory)

后端 未结 3 1837
-上瘾入骨i
-上瘾入骨i 2021-02-12 20:13

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

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-12 20:22

    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.

提交回复
热议问题