What is the difference between a computed property and a property set to a closure?
What is the difference between a computed property and a property set to a closure?
In Swift, the difference between a computed property and a property set to a closure primarily revolves around how and when the property's value is determined and accessed.
A computed property does not store a value directly. Instead, it provides a getter (and optionally a setter) to compute the value each time it is accessed. This means that the computation happens every time the property is called, ensuring that the value is always up-to-date based on the current state of the object.
Example:
var pushBehavior: UIPushBehavior {
get {
let lazilyCreatedPush = UIPushBehavior()
lazilyCreatedPush.setAngle(50, magnitude: 50)
return lazilyCreatedPush
}
}
In this example, each time pushBehavior
is accessed, a new UIPushBehavior
object is created and configured.
A property set to a closure, on the other hand, is a stored property that is initialized using a closure. The closure is executed only once, at the time of initialization, and the result is stored in the property. This means that the value is computed once and then reused every time the property is accessed.
Example:
var pushBehavior: UIPushBehavior = {
let lazilyCreatedPush = UIPushBehavior()
lazilyCreatedPush.setAngle(50, magnitude: 50)
return lazilyCreatedPush
}()
In this example, the closure is executed once when pushBehavior
is initialized, and the resulting UIPushBehavior
object is stored in the property. Subsequent accesses to pushBehavior
will return the same object.
Execution Frequency:
Mutability:
var
, allowing the stored value to be changed after initialization.Use Cases:
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào