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! While you're at it, check out some resources Treehouse students have shared here.

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

iOS

A little confused on how exactly this snipet of code works

So, a little confused here.

What's the 0 for? Where did total and score come from? are they variables? Also, why is in there?

let scores = [10,12,11,10,12,9]
let totalScore = scores.reduce(0, combine: {total, score in total + score })

1 Answer

Reduce is a higher order function that have the same result as the following:

let scores = [10,12,11,10,12,9]
var totalScore = 0
for score in scores {
    totalScore += score
}

With reduce you can write it like you did above. 0 represents totalScore's initial value. Combine is a function that combines two values. You named these values total and score, so you use those values to access totalScore and score in the function. Last but not least you add score to total and have the total score as result.

Ahhh I see, Thank you so much!