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

I was just wondering if anyone could break this down and explain to me how this works...?

let numbers = [2,8,1,16,4,3,9] var sum = 0 var counter = 0

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

print(sum)

Thank You! That makes so much sense now.

1 Answer

Hey Michael, I've posted your code with my comments below. Hope this helps.

//declares an array of Int's named numbers
let numbers = [2,8,1,16,4,3,9]
//declares an Int variable named sum, initialised with a zero value
//used to keep track of the sum total
var sum = 0
//declares an Int variable named counter, initialised with a zero value
//this is used as an index value, as well as an indicative value
//to compare to the number of items in the numbers array
var counter = 0

//While Loop
//This should read as "While the counter is less than the amount of items in the numbers array, execute the below."
//While this conditional is true, the body of the loop will execute.
while counter < numbers.count {
    //The += operator takes the current value of sum, and adds
    //the number at the index specified by the counter property.
    //can also be written as sum = sum + numbers[counter]
    sum += numbers[counter]
    //We then add 1 onto the current counter property so that
    //the index next time will be one more than this execution.
    //If this was the last index in the array, the boolean
    //of the while loop condition will become false and stop executing
    //because the counter is now higher than the amount of items in the numbers array.
    counter += 1
}