← Back to Swift Course | Chapter 7: Closures | Lesson 5 of 6

Autoclosures क्या हैं

एक autoclosure एक चालाक छोटा wrapper है जिसे Swift अपने आप किसी expression के आस-पास जोड़ता है, ताकि यह तब तक असल में compute न हो जब तक आप इसे उपयोग करना तय न करें।
Syntax
swift
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

markup
// 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")

Why Autoclosures Delay Evaluation

चूंकि expression एक closure में wrapped है, यह सिर्फ तब evaluate होता है जब closure असल में function के अंदर call हो, जो अनावश्यक काम से बच सकता है।

Note: यह बिल्कुल वही है कि ?? अपनी right-hand side evaluate करने से कैसे बचता है जब तक left side nil न हो।

उदाहरण: Why Autoclosures Delay Evaluation

markup
// 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")
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. Regular parameters के लिए @autoclosure overuse करना; यह किसी expression की evaluation delay करने के लिए है, एक general-purpose convenience नहीं।
  2. यह भूल जाना कि एक @autoclosure parameter call site पर एक normal expression की तरह call किया जाता है, explicit closure braces के साथ नहीं।
  3. यह न समझना कि 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:

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.