swift逃逸閉包

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.