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

Lost here: Using the value of counter as an index value, retrieve each value from the array and add it to the value of s

Does that mean I need to retrieve the value of counter inside the while loop?

Also what is the code to retrieve a value?

Would is just be sum = numbers[1] ?

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

// Enter your code below
while counter < 1 {
    counter += 1
     sum += newValue
}

1 Answer

Jhoan Arango
Jhoan Arango
14,575 Points

Hello,

So the challenge wants you to use counter as the index to retrieve the numbers inside the array.

Why use counter ? The reason why we want to use the counter to retrieve those numbers is because we are going to make it Increase in value every time the loop runs.

The challenge also says to use the while loop and make it run as long as the counter is less than the amount of values inside the array. In this case we can use the instance method count.

while counter < numbers.count { // Here we check that counter is less than numbers array

 sum += numbers[counter] // We use counter as an index to retrieve the values

 counter += 1 // We add one number to counter
}

Things to remember:

To retrieve a value from an array you have to use its subscript.

let value = array[1]

A while loop will keep running until a condition is true.

Good luck, hope this helps