← Back to Swift Course | Chapter 11: Error Handling | Lesson 5 of 6

defer Statement की जानकारी

defer code के current block से निकलने से ठीक पहले कुछ करने का एक वादा है, चाहे आप कैसे भी इससे निकलें।
Syntax
swift
func functionName() {
    defer {
        // cleanup: runs when the scope exits
    }
    // main work
}

Basic defer Usage

एक defer block वहां लिखा जाता है जहां cleanup logic conceptually belong करता है, लेकिन Swift इसे असल में चलने में तब तक delay करता है जब तक function exit होने वाला न हो।

उदाहरण: Basic defer Usage

markup
// Define the function `processFile` with no parameters
func processFile() {
    // Print "Opening file" to the console
    print("Opening file")
    defer {
        // Print "Closing file" to the console
        print("Closing file")
    }
    // Print "Processing file" to the console
    print("Processing file")
}
processFile()

Multiple defer Blocks Run in Reverse Order

जब एक scope में कई defer blocks हों, वे इन्हें लिखे जाने के उल्टे order में execute होते हैं, एक stack जैसा।

उदाहरण: Multiple defer Blocks Run in Reverse Order

markup
// Define the function `demo` with no parameters
func demo() {
    defer { print("First defer (runs last)") }
    defer { print("Second defer (runs first)") }
    // Print "Function body" to the console
    print("Function body")
}
demo()
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. यह मान लेना कि defer जहां लिखा गया है वहीं तुरंत चलता है; यह असल में हमेशा enclosing scope के बिल्कुल आखिर में चलता है।
  2. कई defer blocks लिखना और उन्हें लिखे गए order में चलने की उम्मीद करना; वे असल में उल्टे order में चलते हैं, last-in-first-out।
  3. defer का उपयोग उस logic के लिए करना जिसे सिर्फ success पर conditionally चलना चाहिए; defer हमेशा चलता है चाहे scope normally exit हो या एक thrown error के ज़रिए।
चैप्टर सारांश
  • defer { } code को current scope exit होने से ठीक पहले चलने के लिए schedule करता है, यह चाहे कैसे भी exit हो।
  • कई defer blocks उल्टे (last-in-first-out) order में चलते हैं।
  • defer आमतौर पर cleanup के लिए उपयोग होता है, जैसे एक resource बंद करना, जो हमेशा होना चाहिए।
  • defer तब चलता है चाहे scope normally exit हो, return से, या एक thrown error से।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.