Using Lazy var downsides

Hi all,
im here to ask a simple question :slight_smile: : is there any downsides of using lazy var like in compilation time or runtime speed .. ?

In my project i really like to have everything related to a var (specially UI components) in one place (layout, label text, colours ..) so i use lazy to create my label (if there's dependencencies between properties, in this case i don't use lazy because it will lead to infinite loop).

here's an exemple:

  private lazy var labelDescription: UILabel = {
     let label = UILabel(frame: .zero)
     label.numberOfLines = 0
     label.text = self.computedText()
     label.translatesAutoresizingMaskIntoConstraints = false
     label.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true

     return label 

}

Thanks :+1:

Lazy properties compile into optionals, so the result is just a couple of machine instructions or so worth of overhead, which is generally so marginal that you should't have a reason to worry about it.

2 Likes

One downside which I know is that lazy var initialisation isn't atomic. So if you access uninitialised lazy var from multiple threads it might crash the process.

1 Like

yes im aware about this limitation and this is why i use it mostly for UI component :slight_smile:

Terms of Service

Privacy Policy

Cookie Policy