Generic Functions क्या हैं
एक generic function एक बार लिखा जाता है लेकिन आप जो भी type इसे देते हैं लगभग उसके साथ काम करता है, एक universal adapter जैसा।
In this page:
Syntax
func functionName<T>(_ param: T) -> T {
return param
}
func functionName<A, B>(_ a: A, _ b: B) -> (A, B) {
return (a, b)
}
Writing a Generic Function
एक generic function अपने नाम के बाद angle brackets में एक placeholder type declare करता है, जो फिर call होने पर उपयोग किए गए किसी भी concrete type के लिए stand in करता है।
उदाहरण: Writing a Generic Function
func firstAndLast<T>(_ items: [T]) -> (T, T)? {
guard let first = items.first, let last = items.last else { return nil }
// Return `(first, last)` from this function
return (first, last)
}
// If `firstAndLast([1, 2, 3, 4])` has a value, bind it to `result`
if let result = firstAndLast([1, 2, 3, 4]) {
// Print "First: \(result.0), Last: \(result.1)" to the console
print("First: \(result.0), Last: \(result.1)")
}
// If `firstAndLast(["a", "b", "c"])` has a value, bind it to `result`
if let result = firstAndLast(["a", "b", "c"]) {
// Print "First: \(result.0), Last: \(result.1)" to the console
print("First: \(result.0), Last: \(result.1)")
}
Login to try C/C++/Java/PHP code in the editor
Multiple Generic Placeholders
एक generic function एक से ज़्यादा placeholder type declare कर सकता है, इसे अलग-अलग types के combinations में एक साथ काम करने देते हुए।
उदाहरण: Multiple Generic Placeholders
func makePair<A, B>(_ first: A, _ second: B) -> (A, B) {
// Return `(first, second)` from this function
return (first, second)
}
// Declare a constant `pair`, set to `makePair(1, "one")`
let pair = makePair(1, "one")
// Print `pair` to the console
print(pair)
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. #}
आम गलतियां
Int,String,Double, वगैरह के लिए near-identical functions लिखना जब एक placeholder type वाला single generic function इन सभी के लिए काम करता।- यह भूल जाना कि placeholder type नाम (जैसे
T) को function नाम के ठीक बाद angle brackets में declared होना चाहिए। - यह मान लेना कि एक generic placeholder
Tकुछ भी कर सकता है; यह सिर्फ उन operations को support करता है जो हर possible type के लिए valid हैं, जब तक आगे constrained न हो।
चैप्टर सारांश
- एक generic function एक placeholder type उपयोग करता है, convention से
T, angle brackets में declared। - Placeholder call site पर determined एक असली type के लिए stand in करता है।
- Generic functions कई concrete-typed versions में logic duplicate करने से बचते हैं।
- Constraints के बिना, एक generic type सिर्फ उन operations को support करता है जो बिल्कुल किसी भी type के लिए valid हैं।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: