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 Collections and Control Flow Control Flow With Loops Working With Loops

Challenge Task 2 of 2

I'm unable to finish challenge task 2 of 2. Where can I find the answer so that I can self evaluate, learn what I did wrong and continue the course? Really frustrating that I'm unable to look up the answer after 15 failed tries with different lines of code.

Anthony Lafont
Anthony Lafont
17,075 Points

Hi Jochen,

The best way is to post your code. We can't do anything for you if we don't know what you're doing wrong!

3 Answers

Anthony Lafont
Anthony Lafont
17,075 Points

No problem Jochen ;)

In your first proposition, you were very close to the answer!

The problem was just because of your condition in the while loop.

You're telling the compiler that it has to loop while the counter is inferior OR EQUAL to the number.count.

By doing this that way, the last iteration of the loop will be the following:

while counter <= numbers.count {  // 9nth time iteration
sum += numbers[8] // Here is the problem, there is no 9th element in the array. So the compiler is returning an error
counter += 1 
}

So you only have to change the condition to be right

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

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

Anthony

Thanks Anthony, that makes sense. I have a long way to go ;-)

Thanks for the quick reply Anthony.

I'm trying to finish the challenge currently as follows:

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

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

or by doing this:

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

while counter <= numbers.count { 
sum = sum + newValue 
counter += 1 
}

Sorry had to edit it a couple of times to match the syntaxes of the Forum, so it would show right. It's my first time posting stuff on the community here so trying to get the hang of it all :)