David Seek David Seek - 1 year ago 68
Swift Question

What is the advantage of a lazy var in Swift

What is the advantage or difference of initializing:

lazy var hintView: HintView = {
let hintView = HintView()
return hintView

Instead of simply use:

var hintView = HintView()

class HintView: UIView {}

Help is very appreciated.

Answer Source

Lazy Stored Property vs Stored Property

There are a few advantage of a lazy property over a stored property.

  1. The closure associated to the lazy property is executed only if you read that property. So if for some reason that property is not used (maybe because of some decision of the user) you avoid unnecessary allocation and computation.
  2. You can populate a lazy property with the value of a stored property.
  3. You can use self inside the closure of a lazy property
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download