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

whats wrong?

dont understand whats wrong with this code

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


while counter < numbers.count {
  sum += (numbers.count)
  counter++ }


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

2 Answers

Keli'i Martin
Keli'i Martin
8,227 Points

I'm not sure why you have two while loops but you don't need the first one at all. The second while loop has the exact code you need to pass the challenge.

Tobias Helmrich
Tobias Helmrich
31,603 Points

Hey there,

the code of the second while loop is actually perfectly fine! The first one however is wrong because you're just adding the length of the numbers array to the sum variable all the time but you have to add the value at the current index to the sum variable which you're doing correctly in the second loop. The first while loop is also the reason why you're not passing the challenge, so if you remove it, it should work!

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

I hope that helps! :)