defer Statement की जानकारी
defer code के current block से निकलने से ठीक पहले कुछ करने का एक वादा है, चाहे आप कैसे भी इससे निकलें।
In this page:
Syntax
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
// 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()
Login to try C/C++/Java/PHP code in the editor
Multiple defer Blocks Run in Reverse Order
जब एक scope में कई defer blocks हों, वे इन्हें लिखे जाने के उल्टे order में execute होते हैं, एक stack जैसा।
उदाहरण: Multiple defer Blocks Run in Reverse Order
// 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()
Login to try C/C++/Java/PHP code in the editor
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. #}
आम गलतियां
- यह मान लेना कि
deferजहां लिखा गया है वहीं तुरंत चलता है; यह असल में हमेशा enclosing scope के बिल्कुल आखिर में चलता है। - कई
deferblocks लिखना और उन्हें लिखे गए order में चलने की उम्मीद करना; वे असल में उल्टे order में चलते हैं, last-in-first-out। deferका उपयोग उस logic के लिए करना जिसे सिर्फ success पर conditionally चलना चाहिए;deferहमेशा चलता है चाहे scope normally exit हो या एक thrown error के ज़रिए।
चैप्टर सारांश
defer { }code को current scope exit होने से ठीक पहले चलने के लिए schedule करता है, यह चाहे कैसे भी exit हो।- कई
deferblocks उल्टे (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: