iOS Swift Collections and Control Flow Control Flow With Loops Working With Loops

Ryan Rassoli
Ryan Rassoli
3,365 Points

Roadblock...

I took some of this code from this forum (https://teamtreehouse.com/community/working-with-loops-challenge-task-2-of-2) to try and better understand it, but i'm still having issues. I understand everything up to line 8. I don't get where newValue came from. I understand the concept of it but I don't know how to add the value of each individual number from the array to the sum. Could someone please further explain? Also, in the forum counter ++ was used, but it hasn't been taught before and I'm also getting a syntax error on that. Could someone tell me what to replace it with and what it does and how it works? I know its a lot but I would really appreciate if someone could answer these questions in depth. Thanks!!!

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

// Enter your code below
var index = 0
while counter < numbers.count {
    sum = sum + newValue
        counter ++ 
}

1 Answer

Magnus Hållberg
Magnus Hållberg
17,216 Points

The "newValue" variable is a placeholder name the challenge explanation use to explain the syntax and the ++ is just the former way of saying "+= 1". So the code you are asking about should look like below from Swift 3 and on:

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

// Enter your code below
var index = 0
while counter < numbers.count {
    sum = sum + numbers[counter]
        counter += 1
}

You could also update the sum value like this:

    sum += numbers[counter]

Hope this helps