Swift逃逸閉包和非逃逸閉包



Swift 閉包

就像其他程式語言一樣,Swift 也支援閉包。閉包是自包含的功能塊,可以傳遞和使用在程式碼中執行任何特定任務。它可以分配給變數或作為引數傳遞給函式。閉包可以捕獲其周圍上下文中的值,並且可以用作回撥或內聯程式碼。Swift 支援以下型別的閉包:

  • 逃逸閉包
  • 非逃逸閉包

讓我們詳細討論它們。

Swift 中的逃逸閉包

當閉包作為引數傳遞給函式,但該閉包在函式返回後被呼叫時,則這種型別的閉包稱為逃逸閉包。預設情況下,作為引數傳遞給函式的閉包是非逃逸引數,這意味著閉包將在函式執行期間執行。

要將閉包宣告為逃逸閉包,我們必須在表示逃逸閉包的引數型別之前使用@escaping關鍵字。

語法

以下是逃逸閉包的語法:

func methodname(closure: @escaping() -> Void){
   // body

   // Calling the closure
   closure()
}

示例

Swift 程式演示逃逸閉包。

import Foundation

class Operation{
    
   // Method that takes two numbers and an escaping closure to find their product
   func product(_ x: Int, _ y: Int, productResult: @escaping (Int) -> Void) {
    
      // Activating an asynchronous task
      DispatchQueue.global().async {
         let output = x * y
            
         // Calling escaping closure
         productResult(output)
      }
   }
}

// Creating object of Operation class
let obj = Operation()

// Accessing the method
obj.product(10, 4) { res in
   print("Product of 10 * 4 = \(res)")
}

// Activating the passage of time
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
   // It will be executed after a delay, simulating an asynchronous operation
}

輸出

它將產生以下輸出:

Product of 10 * 4 = 40

Swift 中的非逃逸閉包

非逃逸閉包是 Swift 中的預設設定,我們不需要任何特殊符號來表示非逃逸閉包。這種型別的閉包在其傳遞到的函式的執行期間執行,一旦函式的執行結束,閉包將不再可用。它們不會被儲存以供以後執行。它們不會被儲存供以後執行。

語法

以下是非逃逸閉包的語法:

mutating func methodname(Parameters) -> returntype {
   Statement
}

示例

Swift 程式演示非逃逸閉包。

class Operation {
    
   // Function that takes two numbers and a non-escaping closure to calculate their sum
   func sum(_ X: Int, _ Y: Int, add: (Int) -> Void) {
      let result = X + Y
        
      // Calling the non-escaping closure
      add(result)
   }
}

// Creating the object of operation class
let obj = Operation()

obj.sum(10, 12) { add in
   print("sum: \(add)")
}

輸出

它將產生以下輸出:

Sum: 22

逃逸閉包與非逃逸閉包

以下是逃逸閉包和非逃逸閉包的主要區別:

逃逸閉包 非逃逸閉包
它可以超出其傳遞到的函式的生命週期。 它在函式執行期間執行。
它可以儲存為屬性或分配給變數。 它不能儲存,也不允許在函式作用域之外使用。
它通常用於非同步操作,如網路請求等。 它通常用於同步操作,如簡單的計算等。
@escaping 關鍵字用於建立逃逸閉包。 它是預設的閉包,不需要任何特殊的語法。
廣告