iOS Swift Collections and Control Flow Control Flow With Loops While and Repeat While

Michael Cronk
Michael Cronk
7,607 Points

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)

Michael Cronk
Michael Cronk
7,607 Points

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
}