Function Types क्या हैं
एक function type किसी function की shape describe करता है -- यह क्या लेता है और क्या वापस देता है -- ताकि आप किसी function को एक variable में store कर सकें बिल्कुल एक number या string की तरह।
Syntax
let name: (ParamType) -> ReturnType = existingFunction
func functionName(_ op: (ParamType) -> ReturnType) {
// call op(value)
}
Storing a Function in a Variable
चूंकि functions first-class values हैं, एक function को एक variable को assign किया जा सकता है जिसका type इसके signature से मेल खाता हो।
उदाहरण: Storing a Function in a Variable
// Define the function `add` taking `a`, `b` and returning an Int
func add(a: Int, b: Int) -> Int {
// Return `a + b` from this function
return a + b
}
// Declare a constant `operation` (a `(Int, Int) -> Int`), set to `add`
let operation: (Int, Int) -> Int = add
// Print `operation(3, 4)` to the console
print(operation(3, 4))
Login to try C/C++/Java/PHP code in the editor
Passing a Function as an Argument
एक function type को एक parameter type के रूप में उपयोग किया जा सकता है, एक function को किसी दूसरे function को एक argument के रूप में receive करने देते हुए।
उदाहरण: Passing a Function as an Argument
// Define the function `multiply` taking `a`, `b` and returning an Int
func multiply(a: Int, b: Int) -> Int {
// Return `a * b` from this function
return a * b
}
// Define the function `apply` taking `operation`, `a`, `b` and returning an Int
func apply(_ operation: (Int, Int) -> Int, to a: Int, and b: Int) -> Int {
// Return `operation(a, b)` from this function
return operation(a, b)
}
// Print `apply(multiply, to: 3, and: 5)` to the console
print(apply(multiply, to: 3, and: 5))
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. #}
आम गलतियां
- यह भूल जाना कि एक function type
(ParamTypes) -> ReturnTypeलिखा जाता है, function के signature से बिल्कुल मेल खाते हुए, parameter types सहित (labels नहीं)। - किसी भिन्न signature वाले function को एक variable assign करने की कोशिश करना जो पहले से किसी और function shape के लिए typed है।
- एक function type variable को function को असल में call करने के साथ confuse करना -- इसे invoke करने के लिए arguments के साथ
()जोड़ना चाहिए।
चैप्टर सारांश
- किसी function का type
(ParameterTypes) -> ReturnTypeलिखा जाता है। - Functions को variables को assign किया जा सकता है, arguments के रूप में pass किया जा सकता है, और दूसरे functions से return किया जा सकता है।
- यह Swift में functions को first-class values बनाता है।
- एक function type variable को बिल्कुल एक normal function की तरह call किया जाता है, parentheses और arguments के साथ।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: