David Seek David Seek - 21 days ago 5
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()


(
HintView
is:
class HintView: UIView {}
)

Help is very appreciated.

Answer

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