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

Daniel Lambrecht
seal-mask
PLUS
.a{fill-rule:evenodd;}techdegree
Daniel Lambrecht
iOS Development Techdegree Student 5,302 Points

how to use counter to choose which item in the array to add?

ive tried several combinations: sum += numbers[(counter)] sum += numbers[(counter)] sum += numbers[counter]

im lost :D

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

// Enter your code below

while counter <= sum {
    sum += numbers[(counter)]
    counter += 1
}

1 Answer

andren
andren
28,558 Points

You don't need to have parenthesis around the counter variable but that is not actually what causes an issue with your code. The problem is that the condition for the loop is incorrect. The loop is meant to run while counter is less than the number of items in the numbers array. Your looping condition states that it should run until it is less than or equal to the sum variable, which is incorrect.

You can get the number of items in the numbers array using the count property so the loop should look like this:

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

Other than the condition (and the unnecessary parenthesis) your code was correct.