swift逃逸闭包

定义
A closure is said to escape a function when the closure is passed as an argument to the function, but is called after the function returns. When you declare a function that takes a closure as one of its parameters, you can write @escaping before the parameter’s type to indicate that the closure is allowed to escape.
闭包描述为:当闭包作为参数被传递到一个函数的时候,但是调用却在函数return之后。当你声明一个函数,这个函数把闭包作为它的一个参数,你可以把@escaping关键字写在在参数类型之前来表明这个闭包允许逃逸。
应用
One way that a closure can escape is by being stored in a variable that is defined outside the function. As an example, many functions that start an asynchronous operation take a closure argument as a completion handler. The function returns after it starts the operation, but the closure isn’t called until the operation is completed—the closure needs to escape, to be called later. For example:
一种情况下闭包可以逃逸,闭包被存储在定义在函数外边的变量里边。例如:许多开启异步操作的函数把闭包作为完成处理程序。这个函数在开启这个异步操作之后就已经return了。但是这个闭包并不发生调用直到异步操作完成。要实现闭包后来被调用的功能,闭包需要逃逸。例如:
swift逃逸闭包_第1张图片
The someFunctionWithEscapingClosure(_:) function takes a closure as its argument and adds it to an array that’s declared outside the function. If you didn’t mark the parameter of this function with @escaping, you would get a compile-time error.

Marking a closure with @escaping means you have to refer to self explicitly within the closure. For example, in the code below, the closure passed to someFunctionWithEscapingClosure(:) is an escaping closure, which means it needs to refer to self explicitly. In contrast, the closure passed to someFunctionWithNonescapingClosure(:) is a nonescaping closure, which means it can refer to self implicitly.
这个函数把一个闭包做为他的一个参数并且把闭包添加到函数外边声明的一个数组中。如果你不标记这个参数为逃逸闭包的话,你将会得到一个编译错误。
创建一个逃逸闭包意味着你在闭包内部必须显示的引用self。相反,someFunctionWithNonescapingClosure(_:)是一个非逃逸闭包,这意味着它可以隐式地引用自己。
swift逃逸闭包_第2张图片

你可能感兴趣的:(swift)