2

According to https://stackoverflow.com/a/38144190/72437

The reason is that the immediately applied closure {}() is considered @noescape. It does not retain the captured self.


and https://oleb.net/blog/2016/10/optional-non-escaping-closures/

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.


However, I still do not understand why @nonescaping closure does not retain self, and doesn't require [weak self]? Can someone explain this concept in simpler manner?

Cheok Yan Cheng
  • 47,586
  • 132
  • 466
  • 875
  • 1
    I don't know how accurate this is, but I find it a useful visualization: a non escaping callback does not escape the function. Meaning it is executed and deallocated before the end of the function scope. A compiler can determine when a non-escaping closure will release self in the same way that it knows when a function would release self. In fact, a non-escaping closure is essentially a function (you can pretty much convert any non-escaping closure to a function). Think of the `map` closure, it is essentially a function that transform an array from one type to another. – Jacob Jul 25 '19 at 05:07
  • In swift you can even pass functions as closures. – Jacob Jul 25 '19 at 05:09
  • Please stop asking the same question repeatedly. – matt Jul 25 '19 at 07:19

2 Answers2

10

The closure does not need to retain self, because the closure itself only lives as long as the function that created it (and self won't go away as long as one of its own functions is still running). So there is no need to keep anything around for longer than the function invocation itself.

You only need to retain something in order to make sure it exists for (at least) as long as you yourself exist (or need access to that thing).

If the closure was escaping the scope of the function that created it, then it could not rely on any of the things it got from that function's scope being kept alive after the function returned. So it has to retain these things itself.

Thilo
  • 257,207
  • 101
  • 511
  • 656
0

A non-escape closure tells the complier that the closure you pass in will be executed within the body of that function so do not need to use weak self.

Varun
  • 61
  • 4