Search code examples
swiftvarlet

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


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 and guides I've seen so far don't use Lazy Var very often, so I'm feeling suspicious that it is bad practice and that I'm overlooking something.

I did a little research and learned that Lazy isn't "thread safe," but I don't understand what this means. I've seen a lot of pros and cons, but I can't draw any conclusions especially because I have very limited knowledge.

When is it ok (or better) to use Lazy Var vs. Let when creating a UIView?

lazy var profileImageView: UIImageView = {

    let imageView = UIImageView(image: #imageLiteral(resourceName: "page1"))
    imageView.translatesAutoresizingMaskIntoConstraints = false
    imageView.contentMode = .scaleAspectFit
    return imageView

}()

Solution

  • Whether you will use lazy var or not depends on your code and its context. It is not bad or good on its own. You have to decide when it is appropriate.

    Before you can decide that, you have to know what lazy var is.

    What is lazy var?

    Lazy initialization is a concept where initialization (construction) of variable content is delayed until its first usage. First access to such variable triggers initialization. Since content is not created until variable is used (needed) using lazy initialized variables can save resources.

    That is primary drive behind lazy initialization. You don't create something until you need it. That is also logic you will use when deciding whether something should be lazy var or not.

    If you are dealing with views (or anything else) that are always visible (needed) there is little point in using lazy initialization. On the other hand when you are dealing with instances that are not always needed - then using lazy var is justified.

    If your view is always visible in presented view controller, you will not accomplish much by making it lazy. If it is visible only under specific circumstances - for instance when user expands some collapsed panel - then making it lazy makes sense. It will make your view controller load faster and use less memory by default.


    As far as thread safety is concerned, lazy var are not thread safe in Swift.

    That means if two different threads try to access the same lazy var at the same time, before such variable has been initialized it is possible that one of the threads will access partially constructed instance.

    You can find more about thread safety in:

    Swift - is lazy var thread-safe?

    Make "lazy var" threadsafe