Swift 中的 Defer 是什麼?
在本教程中,您將學習 defer 關鍵字是什麼以及如何在 Swift 中使用它。您將瞭解在哪些情況下可以使用 defer 關鍵字。
什麼是 defer?
defer 是一個語句,用於在將程式控制權轉移到該語句出現的範圍之外之前執行程式碼。
defer 語句不是您在 Swift 中經常需要使用的語句。當您希望在資源超出範圍之前清理資源時,它會很有用。defer 關鍵字是在 Swift 2.0 版本中引入的。
語法
// Initial tasks to execute before exiting the scope
defer {
// perform cleanup operation here
// other statements
}
// further code
示例
var languages = ["Swift", "Objective-C", "Kotlin", "JavaScript", "Java"] func removeLastValue() -> String? { let lastValue = languages.last defer { languages.removeLast() } return lastValue } let lastValue = removeLastValue() print("last value: \(lastValue ?? "")") print("Array: \(languages)")
輸出
last value: Optional("Java")
Array: ["Swift", "Objective-C", "Kotlin", "JavaScript"]
解釋
您可以檢視輸出,並看到 languages.removeLast() 在上面的示例中的 return 語句之前寫入了。在函式執行完成後,defer 語句將被執行並刪除最後一個元素。
多個 Defer
如果多個 defer 語句出現在相同的範圍內,則它們的執行順序與其出現的順序相反。最後定義的語句將首先執行。最近延遲的事物首先執行——有效地展開一個棧。
示例
func testingMultipleDefer() { defer { print("one") } defer { print("two") } defer { print("three") } print("end of function") } testingMultipleDefer()
輸出
end of function three two one
Defer 不捕獲值
延遲語句不會捕獲變數的引用或當前值。
示例
func captureTest() { var fullName = "Mohit Chouhan" defer { print(fullName) } fullName = "Mohit Sharma" print(fullName) } captureTest()
輸出
Mohit Sharma Mohit Sharma
注意 - 我們不能中斷 defer 的執行,或者我們不能在 defer 塊內部使用 return、continue 或 break。
一個實際的例子
func writeLog() { let file = openFile() defer { closeFile(file) } print("writing all the logs here...") } func openFile() -> String { return "defer_statement.txt" } func closeFile(_ fileName: String) { print("closing file: \(fileName)") } writeLog()
輸出
writing all the logs here... closing file: defer_statement.txt
即使您對已開啟的檔案進行更改,如果您在函式末尾或函式中間返回或退出此函式,defer 塊都會確保檔案將被關閉。
關於 defer 需要記住的要點
defer 不應該嘗試退出當前範圍,因為 'return' 就是為此而存在的。
在離開當前範圍之前,在 defer 塊中執行此類任務(例如清理資源)。
實際上保證無論執行如何離開當前範圍,它都會被執行。
defer 語句僅在執行離開當前範圍時執行,而不是在遇到 defer 語句時執行。
結論
Swift 的 defer 語句在某些情況下對於清理資源非常有用。defer 語句將使您的 iOS 應用程式程式碼平穩執行,即使團隊成員更新方法或新增條件語句。無論我們如何退出,defer 都會執行,並且可以防止專案因可能更改範圍流的更改而導致錯誤,從而降低出錯的可能性。
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP