Can a closure deallocate?

Apple's documentation says that "Define a capture in a closure as an unowned reference when the closure and the instance it captures will always refer to each other, and will always be deallocated at the same time."


So if I understand this correctly, Apple is saying that, in order to define a capture in a closure as an unowned reference. The closure and the instance it captures have to always deallocate at the same time. But how does a closure deallocate? I know that an instance deallocates when there's no strong references to it. But how and when exactly does a closure deallocate?

Accepted Reply

But how and when exactly does a closure deallocate?

A closure deallocates when there's no strong reference to it.

As written in the Swift book, Closures Are Reference Types. Deallocation of closures are managed by ARC.


class MyClass {
    var myClosure: ()->Void = {
        print("closure called")
    }
}

do {
    let myObj = MyClass()
    myObj.myClosure()
} //<-

In this example, you know `myObj` holds strong reference to an instance of MyObj, which is lost at the end of the do-block.

Thus, the instance is deallocated at the end of the do-block.

As well, `myClosure` holds strong reference to the closure, which is lost when the instance is deallocated.

Thus, the closure is deallocated at the end of the do-block.

Replies

The closure will deallocate the instance that it has captured.


Deallocation method depends on the type of the instance. For a view, can be removeFromSuperview

But how and when exactly does a closure deallocate?

A closure deallocates when there's no strong reference to it.

As written in the Swift book, Closures Are Reference Types. Deallocation of closures are managed by ARC.


class MyClass {
    var myClosure: ()->Void = {
        print("closure called")
    }
}

do {
    let myObj = MyClass()
    myObj.myClosure()
} //<-

In this example, you know `myObj` holds strong reference to an instance of MyObj, which is lost at the end of the do-block.

Thus, the instance is deallocated at the end of the do-block.

As well, `myClosure` holds strong reference to the closure, which is lost when the instance is deallocated.

Thus, the closure is deallocated at the end of the do-block.