Passing variable length parameters into function Swift -


this question has answer here:

i reading ibook apple released new language. 1 of experiments suggests write function find average of set of numbers.

here have been trying, getting no feedback playground.

func sumof(numbers: int...) -> int {     var sum = 0     number in numbers {         sum += number     }     return sum }  func calculateaverage(numbers: int...) -> int {     var sum = sumof(numbers)     return sum / numbers.count }  calculateaverage(33, 44, 66, 132) 

on line var sum = sumof(numbers) error:

could not find overload supplied arguments

i having hard time understanding why cannot pass numbers parameter of type int... method takes int...

does know how similar this?

the numbers: int... parameter in sumof called variadic parameter. means can pass in variable number of type of parameter, , pass in converted array of type use within function.

because of that, numbers parameter inside calculateaverage array, not group of parameters sumof expecting.

you might want overload sumof accept either one, this, averaging function can call appropriate version:

func sumof(numbers: int[]) -> int {     var sum = 0     number in numbers {         sum += number     }     return sum } func sumof(numbers: int...) -> int {     return sumof(numbers) } 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -