What is difference between @noescape, @escaping and @autoclosure?

The most important difference is between @escaping and @noescaping (there is no such keyword in Swift 3!). When a closure is marked as @noescape, you can be sure that the closure won't be retained by the method (e.g. to perform an asynchronous call), therefore you don't have to worry about ownership cycles (there are some other minor benefits).

@escaping closures can be saved or called sometimes in the future therefore you have to be sure to handle ownership (e.g. [weak self]) correctly.

For @autoclosure see How to use Swift @autoclosure . In short, it allows you to skip braces around the closure in some situations.

The default (when not specified) is @noescaping in Swift 3 (see rationale). They keyword does not actually exist anymore. There is only @escaping.


@escape means that your function can be called after method ends. @noescape means that your closure will be called before the end of function it passed to. @autoclosure means that you can omit writing closure braces, but it automatically becomes @noescape. @autoclosure creates an automatic closure around the expression. So when the caller writes an expression like 2 > 1, it's automatically wrapped into a closure to become {2 > 1} before it is passed to some function.

2 - Easier for compiler to perform optimisations.

3 - beter to write, to give compiler(or anybody that using your function) information how it behaves with your closure

4 - no

5 - described on the top of the answer

Tags:

Ios

Swift