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

Asad Chishty
Asad Chishty
422 Points

Isn't this the right way to put the counter in the while loop?

I'm a bit confused here.

I tried

while counter < sum.count { print(sum) }

But that was wrong as well.

I'm not sure how I would create a while loop here that would do what the task is asking.

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

// Enter your code below

while sum < numbers.count {

1 Answer

Jennifer Nordell
Jennifer Nordell
Treehouse Teacher

Hi there! I'm guessing that you're stuck on the first step. And you have problems with both versions of your code. Both the one you have here, and the one you tried. The challenge never asks for you to print anything.

In both cases, you are creating an infinite loop. We're going to use counter to keep track of how many times we've gone through the loop. So we should be checking if counter is less than the number of elements in the array. We should then increment counter. If we don't, counter will always retain its original value and the loop will never end. Take a look:

while counter < numbers.count {

This will check to make sure that counter is less than the number of elements that we have in our numbers array. When it executes, counter will be increased by one. This means that at some point the loop will end as the counter will be greater than the number of elements we have.

Hope this helps! :sparkles: