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

MATTHEW WILLIAMS
seal-mask
.a{fill-rule:evenodd;}techdegree
MATTHEW WILLIAMS
iOS Development Techdegree Student 776 Points

Swift Collections and Control Flow Challenge 1

Hi all, I'm having difficulty understanding this question. Just wondering if someone can point me in the right direction?

Many thanks Matt

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

// Enter your code below
while counter.count < numbers.count {

sum += 1

}

1 Answer

Hi Matthew,

You have the syntax correct for the loop however you have not executed what the challenge wants you to do.

Ultimately the solution looks like this:

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

Which translates to: While counter is less than the number of values inside the constant 'numbers' continue executed the loop function. Inside the loop function, counter which starts of as 0 and finishes with a value of 6 (number of values inside 'numbers'), acts as the index number to read the array 'numbers'. Each time the loop reiterates, the subsequent number in 'numbers' is added to sum.

I hope this helps somewhat.

All the best and happy coding,

Mitch

Jenny Dogan
Jenny Dogan
4,595 Points

Hi Mitch, does it matter if you put the counter statement before the sum statement? Thanks!

Hi Jenny,

Yes, because the counter should increase by one each time the while loop reiterates, after the new value is assigned to sum.

It also makes the code more readable.

I hope this helps!

Mitch