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

Diego Aguirre
Diego Aguirre
13,211 Points

Can someone explain another way of achieving this answer?

So here's how I solved this problem. Although I was only able to solve it by plugging it in in Xcode and realizing that initially my index was out of range

sum += numbers[counter]

So my next logical solution was to subtract one from the index like I did below but I want to know if there's another way without having to subtract one. I don't understand also why the counter index would be out of range in the first place?

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

while counter < numbers.count {
    counter++
    sum += numbers[counter - 1]
}
Jose Gallanosa
Jose Gallanosa
14,175 Points

Increment the counter after adding to the sum

sum += numbers[counter]

counter++

1 Answer

Helgi Helgason
Helgi Helgason
7,599 Points

using a for loop

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

for number in numbers{
    sum += number
}