In Swift, the lazy
keyword changes a property so that it is only calculated when it's accessed. This not only makes it useful for performance reasons, it's also incredibly useful for initializing your class when a non-optional property depends on another property for initialization.
Let's look at an example:
class C {
var x: UIView
var y: UIView = {
var v = UIView()
x.addSubview(v)
return v
}()
init() {
x = UIView()
}
}
This class definition compiles with an error because the value of x
is used when computing the value of y
:
error: instance member 'x' cannot be used on type 'C'
This wouldn't work even if you change the definition of x
to:
var x = UIView()
There's an easy fix — just change y
to be lazy
:
class C {
var x: UIView
lazy var y: UIView = {
var v = UIView()
x.addSubview(v)
return v
}()
init() {
x = UIView()
}
}
Because lazy properties are only calculated when they are first used — and you don't use them in your initializer before x
is initialized, this is a very simple fix.
Your feedback is valuable: Do you want more nuggets like this? Yes or No
.
.