← frouo.com


Swift 5

Does lazy var capture self?

lazy var

No.

By default, immediately applied closure {} is considered @noescape by the compiler. Meaning that it doesn't capture self.

Indeed, let's picture that. If your application gets to the point where self.label is calculated, then obviously self exists! The closure can therefore be executed {}() with the guarantee that self exists.

⚠️⤵

This is not to be confused with closure properties that are lazily defined!

lazy var closure

Notice the absence of () at the end of the snippet.

In this case a strong reference is created in the closure, see self.. Unless you specify [unowned self] or [weak self] as you please depending on the context.

References

docs.swift.org - Lazy Stored Properties

A lazy stored property is a property whose initial value is not calculated until the first time it is used. You indicate a lazy stored property by writing the lazy modifier before its declaration.

stackoverflow.com - Lazy initialisation and retain cycle

stackoverflow.com - What is difference between @noescape, @escaping and @autoclosure?

The default (when not specified) is @noescaping in Swift 3 (see swift proposals). They keyword does not actually exist anymore. There is only @escaping.

stackoverflow.com - Must all variable or lazy variable initializer in Swift include weak self?

This is not to be confused with closure properties that are lazily defined!

Thank you

Hope it helps. Please drop a ❤️ on my Twitter post to show your support 🙏.

The source code for this blog is available on GitHub.