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

Austin Knupp
Austin Knupp
2,986 Points

Loops Challenge

The wording of the question is throwing me off. I cannot figure out what I am doing wrong. Please help! :)

loops.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 += numbers.count
print(sum = sum + numbers)
}

1 Answer

Matthew Long
Matthew Long
28,407 Points

You set up the while loop correctly, but the code inside the while loop is incorrect.

When the wording of a question doesn't make sense you can usually predict what they are trying to ask for. For example, your counter adds the length (or count) of numbers each time it is ran. Therefore, it will only run once since counter must be less than numbers.count. It would be logical to predict that the challenge wants you to loop over the values in the numbers array. This would mean you would need to add one to counter at the end of each loop.

Next, the question never asked you to print anything.

Sometimes the wording for the challenges throw me off too. Especially the iOS courses. The iOS course challenges are especially wordy.

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

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

Keep up the hard work!

Austin Knupp
Austin Knupp
2,986 Points

Thank you! My only question then is why do we put "counter" in brackets after "sum += numbers" ?

Matthew Long
Matthew Long
28,407 Points

The counter in the brackets is the index value of the numbers array. The 1st index, 0, of the numbers array has a value of 2. So you add 2 to the sum. The second time through the loop the counter is equal to 1. This is the 2nd index of the numbers array which means you'll add 8 to sum. All the way until counter < numbers.count.