escaping closures

why do escaping closure need to refer to self ?

Basically, it's about memory management (explicit/escaping vs. implicit/non-escaping references).

From the 'net:

-=-

A closure keeps a strong reference to every object the closure captures — and that includes self if you access any property or instance method of self inside the closure, because all of these carry an implicit self parameter.


It’s very easy to accidentally introduce reference cycles in this way, which is why the compiler requires you to explicitly refer to self inside closures. This forces you to think about potential reference cycles and manually resolve them using capture lists.


However, it’s impossible to create a reference cycle with a non-escaping closure — the compiler can guarantee that the closure will have released all objects it captured by the time the function returns. For this reason, the compiler only requires explicit references to self for escaping closures. This makes non-escaping closures significantly more pleasant to use.


Another benefit of non-escaping closures is that the compiler can apply more aggressive performance optimizations. For example, the compiler can omit some retain and release calls when the lifetime of the closure is known. In addition, the memory for a closure’s context can be kept on the stack instead of the heap if the closure is non-escaping — though I don’t know if the Swift compiler currently performs this optimization (an open March 2016 bug report suggests that it doesn’t).

escaping closures
 
 
Q