1. 程式人生 > >swift逃逸閉包

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了。但是這個閉包並不發生呼叫直到非同步操作完成。要實現閉包後來被呼叫的功能,閉包需要逃逸。例如:
這裡寫圖片描述

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(_:)是一個非逃逸閉包,這意味著它可以隱式地引用自己。
這裡寫圖片描述