+ 1
Can someone just explain variadic parameter for swift?
1 Resposta
+ 1
if you want to have a unfixed parameter number function, you can use variadic parameter.
for example:
func avg(num: Double...) -> Double {
var sum = 0.0
var count = 0.0
for i in num {
sum += i
count += 1
}
return sum / count
}
avg(num: 1, 2, 3,4,5) //you get 3. or you can try any number parameter
and yes, you found it is much alike to Array. Actually it can be replace by an array parameter, like this:
func avg(num: [Double]) -> Double {
var sum = 0.0
var count = 0.0
for i in num {
sum += i
count += 1
}
return sum / count
}
avg(num: [1, 2, 3,4,5]) //get the same result