Variadic Parameters क्या हैं
एक variadic parameter एक function को उसी type की कितनी भी values accept करने देता है, zero से लेकर जितनी चाहें उतनी।
Syntax
func functionName(_ params: Type...) {
// params is an array [Type]
}
functionName(value1, value2, value3)
Declaring a Variadic Parameter
किसी parameter के type के बाद ... जोड़ना caller को commas से अलग उस type की कितनी भी values pass करने देता है।
उदाहरण: Declaring a Variadic Parameter
// Define the function `sum` taking `numbers` and returning an Int
func sum(_ numbers: Int...) -> Int {
// Declare a mutable variable `total`, initialized to `0`
var total = 0
// Loop over `numbers`, binding each item to `n`
for n in numbers {
total += n
}
// Return `total` from this function
return total
}
// Print `sum(1, 2, 3)` to the console
print(sum(1, 2, 3))
// Print `sum(10, 20, 30, 40)` to the console
print(sum(10, 20, 30, 40))
Login to try C/C++/Java/PHP code in the editor
Variadic Parameters Are Arrays Internally
Function body के अंदर, एक variadic parameter बस एक regular array है, इसलिए सभी array operations और properties इस पर सीधे काम करते हैं।
उदाहरण: Variadic Parameters Are Arrays Internally
// Define the function `average` taking `scores` and returning a Double
func average(_ scores: Double...) -> Double {
// Return `scores.reduce(0, +) / Double(scores.count)` from this function
return scores.reduce(0, +) / Double(scores.count)
}
// Print `average(80, 90, 70)` to the console
print(average(80, 90, 70))
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 में दो variadic parameters declare करने की कोशिश करना; Swift प्रति function सिर्फ एक variadic parameter allow करता है।
- यह भूल जाना कि एक variadic parameter function के अंदर इसके type के एक plain array के रूप में receive होता है।
- एक variadic parameter को बाकी parameters से पहले बिना उनके बाद वालों पर एक label के रखना, जो Swift disallow करता है ambiguity बनाते हुए।
चैप्टर सारांश
- एक variadic parameter zero या ज़्यादा values accept करता है,
Type...लिखा गया। - Function के अंदर, एक variadic parameter उस type के एक array की तरह behave करता है।
- एक function में ज़्यादा से ज़्यादा एक variadic parameter हो सकता है।
- Callers बस commas से अलग values list करते हैं -- किसी array brackets की ज़रूरत नहीं।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: