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

Bridget Farmer
Bridget Farmer
2,833 Points

Stuck on second code challenge Swift 2.0 Collections and Workflow.

//Question Now that we hav the while loop set up it's time to compute the sum! Using the value of counter as an index value, retrieve each value from the array and add it to the value of sum.

For exampe: sum = sum +newValue. Or you could use the compound addition operator num += newValue where newValue is the value retrieved from the array.

//My code:

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

while counter < numbers.count { print(numbers[counter]) counter++ }

4 Answers

Michael Reining
Michael Reining
10,101 Points

Hi Bridget,

I solved the code challenge without using the newValue variable because I did not feel like it was needed. The shorter version just looks like this.

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

The answer below should also be accepted but it was not. I guess they wanted you to specifically increment the counter using the ++ instead of doing it the other way.

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

One tip... I recommend trying to solve all code challenges in the Playground in Xcode. That way you will get a better feeling for what works.

I hope this helps,

Mike

PS: Thanks to the awesome resources on Team Treehouse, I just launched my first app. :-)

Code! Learn how to program with Swift

Helgi Helgason
Helgi Helgason
7,599 Points
let numbers = [2,8,1,16,4,3,9]
var sum = 0
var counter = 0


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

should work haven't tested it inside the challenge itself. Inside the while loop we create a new variable that's equal to the value of whatever iteration inside numbers we are doing so if the while loop is running for the second time newvalue would be eight since the second value in the numbers array is 8. Then we add that value to the sum variable.