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

Aaron Schokman
PLUS
Aaron Schokman
Courses Plus Student 520 Points

Code is incorrect but does not give reason

Any help would be appreciated

loops.swift
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 += 1
 }

2 Answers

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there! You're correct that it's not giving any message besides "Bummer!". But if you run this in an Xcode playground you'll see that it's encountering an error from which it cannot recover. This is because you are attempting to access an index of the array that doesn't exist. But, if I delete just one character from your code, your code passes!

Here you've written:

while counter <= numbers.count {

But that should be

while counter < numbers.count {

The numbers array contains seven elements, which means that numbers.count is equal to 7. But you cannot access numbers[7] as the last element of the array is at numbers[6]. On the last iteration of the loop counter will be 7 and less than or equal to numbers.count. Because that's true it will run the code block which tries to access numbers[7]. So we need to remove the "or equal to" part.

Hope this clarifies things! :sparkles:

edited to fix clunky wording

Hey Aaron,

It looks like you have mistakenly added in the 'less than or equal too' (<=) operator to your loop.

Just the less than operator (<) is required in order to pass the task, as the code challenges can be very particular in what they are looking for.

Good luck!