swift - cannot invoke avgArray with an argument list of int -
i'm new swift, , start learn language following the swift programming language. in book, there exercise question ask me write function calculate average of array. here code:
func avgarray(elements: int...)->double{ var avg:double = 0 var sum = 0 var count = 0 element in elements { sum += element count += 1 } avg = double(sum) / double(count) return avg } let numberlist = [2,3,6,7,2,7,0,9,12] let average = avgarray(numberlist)
i don't know why can't pass array function. also, there way besides using count variable keep track of number of elements in array?
i don't know why can't pass array function.
your elements
not array, variadic parameter. change
func avgarray(elements: [int])->double{
and should go.
is there way besides using count variable keep track of number of elements in array?
absolutely. count
property of array itself. can use in code this:
avg = double(sum) / double(elements.count)
Comments
Post a Comment