Trailing Closures क्या हैं
एक trailing closure एक shortcut है जहां, अगर एक closure किसी function का आखिरी argument है, आप इसे parentheses के बाहर लिख सकते हैं ताकि call ज़्यादा naturally पढ़े।
In this page:
Syntax
functionName(argument) { param in
// closure body
}
array.map { $0 transformation } // parentheses dropped
Basic Trailing Closure Syntax
किसी closure को parentheses के अंदर pass करने के बजाय, इसे इनके ठीक बाद सीधे लिखा जा सकता है जब यह function का आखिरी argument हो।
उदाहरण: Basic Trailing Closure Syntax
// 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)
}
// Call `operate(5, 6)` with a trailing closure, storing the result in `result`
let result = operate(5, 6) { x, y in
x + y
}
// Print `result` to the console
print(result)
Login to try C/C++/Java/PHP code in the editor
Omitting Parentheses Entirely
जब closure function का इकलौता argument हो, parentheses को पूरी तरह छोड़ा जा सकता है, जो standard library methods के साथ आम है।
उदाहरण: Omitting Parentheses Entirely
// Declare a constant `numbers`, set to `[3, 1, 4, 1, 5]`
let numbers = [3, 1, 4, 1, 5]
// Declare a constant `doubled`, set to `numbers.map { $0 * 2 }`
let doubled = numbers.map { $0 * 2 }
// Print `doubled` to the console
print(doubled)
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. #}
आम गलतियां
- आदतन closure को parentheses के अंदर रखना, जब Swift style इसे एक trailing closure के रूप में बाहर move करने को पसंद करती है।
- यह भूल जाना कि जब किसी function का इकलौता argument एक trailing closure है, parentheses को पूरी तरह omit किया जा सकता है।
- Multiple trailing closures (Swift 5.3+) syntax को confuse करना, जहां बाद वाले closures को अपने खुद के labels चाहिए।
चैप्टर सारांश
- जब एक closure किसी function का final argument हो, इसे closing parenthesis के बाद लिखा जा सकता है।
- अगर closure इकलौता argument है, parentheses को पूरी तरह हटाया जा सकता है।
- यह
.map,.filter, और.sorted(by:)जैसे functions के लिए cleaner, ज़्यादा readable code produce करता है। - Swift 5.3 से multiple trailing closures support किए जाते हैं, हर एक को पहले के बाद अपना खुद का label चाहिए।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: