Nilanshu Jaiswal
Nilanshu Jaiswal

Reputation: 1693

Why escaping closures require us to refer to self explicitly?

Apple's Swift documentation says that:

Marking a closure with @escaping means you have to refer to self explicitly within the closure.

var completionHandlers: [() -> Void] = []

func someFunctionWithEscapingClosure(completionHandler: @escaping () -> Void) {
    completionHandlers.append(completionHandler)
}

func someFunctionWithNonescapingClosure(closure: () -> Void) {
    closure()
}

class SomeClass {
    var x = 10
    func doSomething() {
        someFunctionWithEscapingClosure { self.x = 100 }
        someFunctionWithNonescapingClosure { x = 200 }
    }
}

But I am not able to understand the reason behind this?

In one of his Stanford Lectures (I don't exactly remember which one), Paul Hegarty said that Swift indicates the possibility of retention cycle by forcing you to write self. So is there a possibility of retention cycle while using escaping closures? Or is there any other reason why we have to explicitly refer to self within the closures marked as escaping?

And why in the other case (non escaping closures), there is no possibility of retention cycle?

Thanks in advance.

Upvotes: 1

Views: 431

Answers (1)

cevalloa
cevalloa

Reputation: 142

Self is used to keep/capture the instance of the object you want to send the message. If you don’t use self, then the compiler wouldn’t know where to send the message

The stanford lecture is right, but why does this happen? Having self in a closure can turn into a reference cycle where the object is never let go. You can avoid this by using weak self or unknown self. You should only use weak self or unknown self however to avoid a strong reference cycle.

Let me know if that answers your question properly or if you need anymore help

Upvotes: 2

Related Questions