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 Working with Loops

I got the answer of the forums and honestly have no Idea why this is the answer. Can anyone please explain?

I guess I am confused as to what the variables are for. And what the variables doing in relation to each other inside the code and why they are referencing each other.

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

// Enter your code belowwhile counter < numbers.count {
    var newValue = numbers[counter]
    sum += newValue
    counter++
}

1 Answer

Paul Brazell
Paul Brazell
14,371 Points

It doesn't look like you need the newValue variable.

here is a more simplified solution using a while loop

numbers is the array of numbers you are working with counter is whats used to identify what iteration of the loop you are currently in sum is self explanatory

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

// Cycle through the numbers array and sum its values

while counter < numbers.count {
    sum += numbers[counter]
    counter++  // or counter += 1 (increment and decrement operators are going away in swift 3.0)
}