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

Closure का Syntax

एक closure code का एक टुकड़ा है जिसे आप एक value की तरह अपने साथ ले जा सकते हैं, एक function जैसा लेकिन बिना नाम की ज़रूरत के।
Syntax
swift
let closureName = { (param: Type) -> ReturnType in
    return value
}

functionName(argument, using: { (param: Type) -> ReturnType in
    return value
})

Full Closure Syntax

सबसे explicit closure syntax parameter types, return type, और body से पहले in keyword explicitly बताता है।

उदाहरण: Full Closure Syntax

markup
// Declare a constant `multiply`, set to `{ (a: Int, b: Int) -> Int in`
let multiply = { (a: Int, b: Int) -> Int in
    // Return `a * b` from this function
    return a * b
}
// Print `multiply(3, 4)` to the console
print(multiply(3, 4))

Closures as Function Arguments

एक closure को किसी function में सीधे एक argument के रूप में pass किया जा सकता है जो एक matching function type expect करता है।

उदाहरण: Closures as Function Arguments

markup
// Define the function `operate` taking `a`, `b`, `operation` and returning an Int
func operate(_ a: Int, _ b: Int, using operation: (Int, Int) -> Int) -> Int {
    // Return `operation(a, b)` from this function
    return operation(a, b)
}
let result = operate(5, 6, using: { (x: Int, y: Int) -> Int in
    // Return `x + y` from this function
    return x + y
})
// Print `result` to the console
print(result)
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. in keyword भूल जाना जो किसी closure के parameter list और return type को इसकी body से अलग करता है।
  2. किसी closure के अंदर अनावश्यक type annotations लिखना जब Swift इन्हें पहले से context से infer कर सकता है।
  3. Closure syntax { (params) -> ReturnType in ... } को किसी function की func declaration के साथ confuse करना; closures कभी func keyword उपयोग नहीं करते।
चैप्टर सारांश
  • एक closure { (parameters) -> ReturnType in statements } लिखा जाता है।
  • Closures को variables को assign किया जा सकता है और बिल्कुल functions की तरह call किया जा सकता है।
  • किसी closure के अंदर type annotations अक्सर अनावश्यक होते हैं क्योंकि Swift इन्हें context से infer करता है।
  • Closures अपने आस-पास के scope से variables capture और reference करते हैं।
🔒

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.