Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Roland O'Donnell
5,667 PointsLearning Swft and have a question about code which i don't understand
func average(numbers: Int...) -> Int {
var total = 0
for ave in numbers {
total += ave
}
return total / numbers.count
}
average(23,263,848)
i just want make sure i know whats exactly going on here!
//Why can't i just have
for total in numbers
//and just leave the
total += ave
out of the code??
sorry if i sound stupid..im a beginner
1 Answer

Steve Hunter
57,709 PointsHi Roland,
The function receives numbers
as a parameter. That can hold multiple integers as in your example, it will hold 23, 263 and 848. The purpose of the function is to return the average of those numbers.
The func's purpose is to receive a list of numbers and return the average of those numbers. To form an average, you add up all your numbers and divide by the number of them, right?
So, to add them up, we're iterating through the list of numbers. At each iteration, the number from numbers
is held in the local variable, ave
. At each pass, ave
is added to total
which is set to zero at the start. So, the first loop, ave
will hold 23 which gets added to total
(which is currently zero). Next pass and ave
holds 263 - this is added to total
and so on, one more time with ave
holding the last number, 848. Then total
holds 23 + 263 + 848 = 1,134.
Once we have finished iterating over the numbers, the for
loop ends. We then divide the sum of all the numbers, contained in total
by the number of elements passed in, numbers.count
and return this.
Make sense?
Steve.
Roland O'Donnell
5,667 PointsRoland O'Donnell
5,667 Pointsoh i get it now.. works its way down 1 step 2 step 3 step then back to the top. total += ave is essentially storing the info to the total. thanks for your answer..appreciated.
Steve Hunter
57,709 PointsSteve Hunter
57,709 PointsYep - that's right. The variable
ave
is used to temporarily store each individual number held innumbers
andtotal
holds a rolling sum of those values.