Autoclosures क्या हैं
एक autoclosure एक चालाक छोटा wrapper है जिसे Swift अपने आप किसी expression के आस-पास जोड़ता है, ताकि यह तब तक असल में compute न हो जब तक आप इसे उपयोग करना तय न करें।
Syntax
func functionName(_ condition: @autoclosure () -> Type) {
condition() // expression evaluated only here
}
functionName(expression) // no braces needed
Declaring an Autoclosure Parameter
किसी parameter को @autoclosure चिह्नित करना callers को एक plain expression pass करने देता है, जिसे Swift अपने आप एक closure में wrap करता है जो सिर्फ function के अंदर उपयोग होने पर evaluate होता है।
उदाहरण: Declaring an Autoclosure Parameter
// Define the function `logIfTrue` taking `condition`, `message`
func logIfTrue(_ condition: @autoclosure () -> Bool, message: String) {
// Check whether `condition()`
if condition() {
// Print `message` to the console
print(message)
}
}
logIfTrue(5 > 3, message: "Five is greater than three")
Login to try C/C++/Java/PHP code in the editor
Why Autoclosures Delay Evaluation
चूंकि expression एक closure में wrapped है, यह सिर्फ तब evaluate होता है जब closure असल में function के अंदर call हो, जो अनावश्यक काम से बच सकता है।
Note:
यह बिल्कुल वही है कि
?? अपनी right-hand side evaluate करने से कैसे बचता है जब तक left side nil न हो।उदाहरण: Why Autoclosures Delay Evaluation
// Define the function `describe` taking `value`
func describe(_ value: @autoclosure () -> String) {
// Print "Describing: \(value())" to the console
print("Describing: \(value())")
}
describe("a lazily evaluated string")
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. #}
आम गलतियां
- Regular parameters के लिए
@autoclosureoveruse करना; यह किसी expression की evaluation delay करने के लिए है, एक general-purpose convenience नहीं। - यह भूल जाना कि एक
@autoclosureparameter call site पर एक normal expression की तरह call किया जाता है, explicit closure braces के साथ नहीं। - यह न समझना कि autoclosures का पूरा point lazy evaluation है -- अगर लापरवाही से उपयोग किया जाए, expression के अंदर side effects उम्मीद के अनुसार न चलें।
चैप्टर सारांश
@autoclosureअपने आप एक plain expression argument को एक closure में wrap करता है।- यह expression की evaluation को तब तक delay करता है जब तक closure असल में function के अंदर call न हो।
- यह call sites को explicit closure braces चाहने के बजाय एक normal expression जैसा दिखने देता है।
- Swift का built-in
assertऔर??lazy evaluation के लिए internally autoclosures उपयोग करते हैं।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: