What exactly would you like to know?
"lazy var" is the beginning of the lazy stored property declaration.
This is a kind of property that is not initialized during object creation process but rather when it is needed for the first time.
This behavior is useful for example in case of UIViewController when you would like to create in code a button and store it as an instance property:
class ViewController: UIViewController {
lazy var button: UIButton = {
let button = UIButton(type: .system)
button.addTarget(self, action: #selector(handleTap), for: .touchUpInside)
return button
}()
@objc func handleTap() {}
}
If you try to run this code as a regular let/var property, there will be compilation error, because "self" in (button.addTarget method call) hasn't been created yet.
When "self" may be considered as created?
- during initialization process (init() call)
And now... regular stored properties are initialized first. Even prior to initializers ("self" doesn't exist - compilation error). Whereas lazy properties, as I said, are initialized when needed for the very first time. This can be at least in initializer or anytime later ("self" exists - no compilation errors).
I hope this helped.
Brian, could you add some code formatting / syntax highlighting options to this message boxes? :D