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

后端 未结 3 1841
-上瘾入骨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:18

    The use of lazy vars can provide a workaround to a paradoxical problem: You want to create a custom view that has subviews whose initialization refers to the parent view.

    For example, if you want to create a subclass of UIView that contains a child UIScrollView of the same size, you can't declare a class containing:

    var m_scrollView: UIScrollView
    
    override init(frame: CGRect)
    {
        m_scrollView = UIScrollView(frame: self.frame)
        super.init(frame: frame)
    }
    

    The compiler will complain that you're referring to self before calling super.init. But... super.init has to be called after all members are initialized.

    The solution to this circular problem is making m_scrollView lazy and initalizing it in its declaration:

    lazy var m_scrollView = UIScrollView(frame: self.frame)
    

提交回复
热议问题