Swift -- escape closure and non-escape closure (Swift3.1), swift -- swift3.1
Escape closure and non-escape closure:
There are two types of closures in Swift: Escape closure and non-escape closure. The escape closure indicates that the closure will be executed after the function is returned, while the non-escape closure indicates that the function is executed internally before the function is returned.
Can we understand it as follows: if a closure is used as a parameter of a function, when the closure is executed, the closure is an escape closure if it is asynchronous; if it is synchronous, the closure is a non-escape closure.
Escape closure conditions:
The escape closure must meet the following two conditions:
1. The closure is uploaded to the function as a parameter.
2. The closure is executed only after the function returns.
Add the annotation @ escaping before the parameter to indicate that the closure allows "escape" from this function.
Note: marking a closure as @ escaping means you must explicitly reference it in the closure.
Closure capture policy changes in Swift3.0:
In Swift2.0, the closure capture policies of a function parameter are escape by default. to indicate a non-escape closure, you need to use the @ noescape keyword to modify the closure. Most people tend to ignore and determine whether the closure is escaped when writing the closure parameter. If the closure is treated as an escape closure, the memory management optimization of the closure is not very friendly. Therefore, in Swift3.0, this was changed: All closures are non-escape closures by default, and @ noescape is discarded. To indicate the escape closure, use the @ escaping keyword to modify the closure.
Instance:
The following code calls back is executed 1 second after the function is executed, so it is an escape closure.
func startRequest(callBack: ()->Void) { DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + 1) { callBack() } }
In this way, the @ escaping must be explicitly declared before compilation can pass