Closure का Shorthand Syntax
In this page:
array.sorted { a, b in a < b } // inferred types, implicit return
array.map { $0 * 2 } // shorthand names $0, $1
array.sorted(by: >) // operator as closure
Type Inference and Implicit Return
जब Swift पहले से context से किसी closure का expected type जानता है, closure explicit types और single expression के लिए return keyword छोड़ सकता है।
उदाहरण: Type Inference and Implicit Return
// Declare a constant `numbers`, set to `[4, 2, 7, 1]`
let numbers = [4, 2, 7, 1]
// Declare a constant `sorted`, set to `numbers.sorted { a, b in a < b }`
let sorted = numbers.sorted { a, b in a < b }
// Print `sorted` to the console
print(sorted)
Login to try C/C++/Java/PHP code in the editor
Shorthand Argument Names
Swift अपने आप $0, $1, वगैरह किसी closure के parameters के नाम के रूप में प्रदान करता है, आपको छोटे closures के लिए इन्हें नाम देने से पूरी तरह बचने देते हुए।
उदाहरण: Shorthand Argument Names
// Declare a constant `numbers`, set to `[4, 2, 7, 1]`
let numbers = [4, 2, 7, 1]
// Declare a constant `doubled`, set to `numbers.map { $0 * 2 }`
let doubled = numbers.map { $0 * 2 }
// Declare a constant `sorted`, set to `numbers.sorted { $0 < $1 }`
let sorted = numbers.sorted { $0 < $1 }
// Print `doubled` to the console
print(doubled)
// Print `sorted` to the console
print(sorted)
Login to try C/C++/Java/PHP code in the editor
Passing an Operator as a Closure
जब किसी operator का signature expected closure type से बिल्कुल मेल खाता है, इसे एक closure लिखने के बजाय सीधे नाम से pass किया जा सकता है।
उदाहरण: Passing an Operator as a Closure
// Declare a constant `numbers`, set to `[4, 2, 7, 1]`
let numbers = [4, 2, 7, 1]
// Declare a constant `descending`, set to `numbers.sorted(by: >)`
let descending = numbers.sorted(by: >)
// Print `descending` to the console
print(descending)
Login to try C/C++/Java/PHP code in the editor
- Complex logic वाले closures के लिए
$0,$1shorthand overuse करना, readability नुकसान पहुंचाते हुए; shorthand छोटे, simple closures के लिए सबसे अच्छा है। - एक single-expression closure body में
returnलिखना; यह वहां implicit और optional है लेकिन multi-statement closures में ज़रूरी है। - यह भूल जाना कि
+या>जैसे operator functions को सीधे एक closure के रूप में pass किया जा सकता है जब उनका signature बिल्कुल मेल खाता हो।
- Swift किसी known function signature को pass किए closure में parameter और return types infer कर सकता है।
$0,$1, वगैरह किसी closure के parameters को positionally refer करते हैं उन्हें नाम दिए बिना।- एक single-expression closure body
returnkeyword छोड़ सकता है। +,<, या>जैसे operators को सीधे एक two-parameter function type से मेल खाने वाले closures के रूप में pass किया जा सकता है।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: