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

發佈了74 篇原創文章 · 獲贊 6 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章