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

Jeongeui Ji
Jeongeui Ji
3,761 Points

So frustrated... I thought I got this question right...

I don't know why but it still says i got a wrong answer... the condition is right... the statement allows the addition between sum and numbers that will increase by one as counter will be added by one, too.

What is wrong with my code? Please teach me what has been done wrong...

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

// Enter your code below
while counter < numbers.count{
print(numbers[counter])
counter++
}

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

2 Answers

Moritz Lang
Moritz Lang
25,909 Points

Hey, your logic works great. The only mistake you made is printing the number instead of adding it to sum. Change your code to the following lines and it should work:

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

// Enter your code below
while counter < numbers.count {
    sum += numbers[counter]
    counter++
}
Jeongeui Ji
Jeongeui Ji
3,761 Points

Thanks Moritz. I did it the way you showed, too. But it didn't work... I don't understand why... I have been stuck in this question for 3 days... I can't go ahead...

Moritz Lang
Moritz Lang
25,909 Points

Jeongeui Ji Can you tell me why it's not working? Do you get an error or something?

Jeongeui Ji
Jeongeui Ji
3,761 Points

it says "make sure you are adding the values retrieved from the array to the sum variable" I don't really get it... please help me Mortiz... And Thank you so much!! I really appreciate your help!!!

Moritz Lang
Moritz Lang
25,909 Points

Did you reload the challenge page? I've tested it once more and I can pass the challenge by pasting in the code I wrote above.