Sobes.tech
Junior — Middle

Explain the key difference between closures that allow escaping their scope and those that cannot.

sobes.tech AI

Answer from AI

In iOS (Swift/Objective-C), closures can capture variables from the outer scope. The key difference between closures that can outlive their scope and those that cannot is related to lifetime and context capture:

  • Closures that can outlive their scope are objects that capture references to variables from the external context and retain them, allowing the use of these variables even after the original scope has ended. Such closures are usually stored in properties, passed as callbacks, etc.

  • Closures that cannot outlive their scope are those that are not stored or do not capture context, or are used only within the same scope where they are defined. They cannot be called later because the context has already been destroyed.

Example:

func makeIncrementer(amount: Int) -> () -> Int {
    var total = 0
    let incrementer: () -> Int = {
        total += amount
        return total
    }
    return incrementer
}

let inc = makeIncrementer(amount: 5)
print(inc()) // 5
print(inc()) // 10

Here, the incrementer closure captures the variables total and amount and retains them, allowing their use outside the original function. If the closure did not capture the context or was not stored, it would not be able to work after exiting the function.

Explain the key difference between closures that… - sobes.tech