Escaping Closures क्या हैं
func functionName(_ completion: @escaping () -> Void) {
storage.append(completion) // stored and called later
}
func other(_ action: () -> Void) {
action() // non-escaping: run before returning
}
Declaring an Escaping Closure Parameter
किसी closure parameter को @escaping चिह्नित करना इसे store (उदाहरण के लिए, एक array में) और बाद में invoke होने देता है, यहां तक कि जो function इसे receive करता है उसके return होने के बाद भी।
उदाहरण: Declaring an Escaping Closure Parameter
// Declare a mutable variable `savedCompletions` (a `[() -> Void]`), initialized to `[]`
var savedCompletions: [() -> Void] = []
// Define the function `saveCompletion` taking `completion`
func saveCompletion(_ completion: @escaping () -> Void) {
// Append `completion` to `savedCompletions`
savedCompletions.append(completion)
}
saveCompletion { print("Completion 1 ran") }
saveCompletion { print("Completion 2 ran") }
// Loop over `savedCompletions`, binding each item to `completion`
for completion in savedCompletions {
completion()
}
Login to try C/C++/Java/PHP code in the editor
Non-Escaping by Default
Closures default रूप से non-escaping होते हैं, मतलब इन्हें function के return होने से पहले call किया जाना चाहिए -- यह ज़्यादा memory-efficient है और यही .map के closure argument को @escaping के बिना सुरक्षित बनाता है।
उदाहरण: Non-Escaping by Default
// Define the function `runImmediately` taking `action`
func runImmediately(_ action: () -> Void) {
// Print "About to run" to the console
print("About to run")
action()
// Print "Finished running" to the console
print("Finished running")
}
runImmediately {
// Print "Running the action now" to the console
print("Running the action now")
}
Login to try C/C++/Java/PHP code in the editor
- किसी closure parameter को
@escapingचिह्नित करना भूल जाना जब यह एक property में stored हो या function के return होने के बाद call हो -- compiler इसे flag करेगा। - यह मान लेना कि सभी closures को
@escapingचाहिए; एक closure को इसकी ज़रूरत सिर्फ तब है जब यह function call से ज़्यादा जीए, जैसे बाद के लिए stored या asynchronously उपयोग किया गया। [weak self]उपयोग किए बिना एक stored escaping closure के अंदरselfको strongly capture करके एक strong reference cycle बनाना।
- एक closure parameter को
@escapingचिह्नित किया जाना चाहिए अगर यह stored हो या function के return होने के बाद call हो। - Non-escaping closures (default) को सिर्फ function call के दौरान ही उपयोग किया जाना चाहिए।
- Escaping closures completion handlers और asynchronous callbacks के लिए आम हैं।
- एक stored escaping closure में
selfcapture करना एक retain cycle का जोखिम रखता है जब तक सावधानी से handle न किया जाए।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: