In short, the first is a stored property that is initialized via a closure, with that closure being called only one time, when it is initialized. The second is a computed property whose get
block is called every time you reference that property.
The stored property’s initialization closure is called once and only once, but you can later change the value of the stored property (unless you replace var
with let
). This is useful when you want to encapsulate the code to initialize a stored property in a single, concise block of code.
The computed property’s block, however, is called each time you reference the variable. It’s useful when you want the code to be called every time you reference the computed property. Generally you do this when the computed property needs to be recalculated every time you reference the stored property (e.g. recalculated from other, possibly private, stored properties).
In this case, you undoubtedly want the stored property (the first example), not the computed property (the second example). You presumably don't want a new push behavior object each time you reference the variable.
By the way, in your first example, you internally reference to it being instantiated lazily. If you want that behavior, you must use the lazy
keyword:
lazy var pushBehavior: UIPushBehavior = {
let behavior = UIPushBehavior()
behavior.setAngle(50, magnitude: 50)
return behavior
}()
If, however, the property is static
, it is automatically instantiated lazily.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…