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 Swift 2.0 Collections and Control Flow Control Flow With Loops While and Repeat While

Subah Jain
Subah Jain
1,775 Points

Part 2 of the Code Challenge

I just don't understand the second part of the code challenge.

I figured the solution would be the following:

while counter < numbers.count { sum += numbers[counter++] }

But how? It is very confusing... What's happening inside the while loop?

1 Answer

It goes like this

while counter < numbers.count { 
/*counter is 0 the first time we enter the loop
* 0 is less than numbers.count which contains a total of 7 items
*/
  sum += numbers[counter];
  //sum was 0 but after we cross this line of code sum becomes the addition of the element at
  //the counter position each time we go through the loop.

  //This is equivalent to saying  sum = sum + numbers[counter]
  //first time we enter the loop sum = 0 + numbers[0] = 0 + 2
  //second time: sum = 2 + numbers[1] = 2 + 8 = 10... and so on
  counter++;
  //we have to increment counter, if we dont, we would have an infinite loop on position 0 which
  //means our code would keep running till eternity on the same position
}
Subah Jain
Subah Jain
1,775 Points

Thank you so much, I got it :)