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

While loop question.

Hey guys, I was just wondering, why is the code im writing here not ok? Thanks.

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 {
counter++
sum = sum + (numbers[counter])
}

1 Answer

Henrik Brüntrup
Henrik Brüntrup
5,485 Points

Hi Justus,

arrays start at 0, not at 1. So your code should look like:

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

// Enter your code below
while counter <= (numbers.count - 1) {

    sum = sum + numbers[counter]
    counter += 1
}

Adding array positions 0 though 6. Yours was 1 through 7, throwing an out of index range since you do not have a position 7 in your array.

Best regards, Henrik

Henrik Brüntrup
Henrik Brüntrup
5,485 Points

You might have to use

counter ++

as

counter += 1

is Swift 3.0 syntax.

Let me know if this works!

J.D. Sandifer
J.D. Sandifer
18,813 Points

Just to clarify for any folks new to programming reading this answer, flipping the order of counter++ and sum = sum + numbers[counter] was the main issue.

The comparison counter <= (numbers.count - 1) is equivalent to counter < numbers.count. However, counter++ has been deprecated as Henrik pointed out in the next answer. You should use counter += 1 instead.

And just for fun, sum = sum + numbers[counter] can be re-written as sum += numbers[counter] for more brevity.