Câu hỏi phỏng vấn Swift
Câu hỏi

What is the difference between a computed property and a property set to a closure?

Câu trả lời

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.

Computed Property

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:

swift Copy
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.

Property Set to a Closure

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:

swift Copy
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.

Key Differences

  1. Execution Frequency:

    • Computed Property: The getter is called every time the property is accessed, recomputing the value each time.
    • Property Set to a Closure: The closure is executed only once during initialization, and the result is stored and reused.
  2. Mutability:

    • Computed Property: Typically read-only unless a setter is provided.
    • Property Set to a Closure: Can be mutable if declared with var, allowing the stored value to be changed after initialization.
  3. Use Cases:

    • Computed Property: Useful when the value needs to be recalculated based on other properties or the current state of the object.
    • Property Set to a Closure: Useful for initializing complex properties in a concise manner, especially when the value does not need to change aft...
middle

middle

Gợi ý câu hỏi phỏng vấn

senior

What is the difference between functions and closures?

expert

What is the difference between @escaping and @nonescaping Closures in Swift?

middle

What does the Swift mutating keyword mean?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào