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

Ryan Maneo
Ryan Maneo
4,342 Points

Yet again questioning my learning abilities

Hello, so often I come across a code challenge like this one:

https://i.imgur.com/STJA2Go.png

I usually get past the first part, as you see. But then later come across a phrase like "retrieve" which was not used in the class, so i ask myself "Does he mean assign the value? Does he mean type the variable newValue and equal it to counter? What does he mean!?!?!" So here I am, yet again.

https://i.imgur.com/RAR0sbc.png

Any advice on learning this is welcome, plus how I can get past this code challenge. I've looked back at my practice code and can't match it to this for some reason. Thanks in advance.

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

// Enter your code below


while counter < 7 {
  counter++
  var newValue = counter
  sum += newValue

}

1 Answer

Michael Reining
Michael Reining
10,101 Points

Hi Ryan,

You are very close.

Retrieving the value from an array is the same as saying:

Access the value from the array (i.e. get each item in the array)

How do you access the value of an array? With the index value. The challenge is telling you to use the counter value as the index value.

If you do that, you end up with this.

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

// Enter your code below

while counter < 7 {

    var newValue = numbers[counter] // retrieve value of numbers array using the counter value
    sum += newValue // update the sum
    counter++ // increment counter at end when you are done with everything

}

I hope that helps,

Mike

PS: Thanks to the awesome resources on Team Treehouse, I launched my first app.

Now you can practice writing Swift code directly on your iPhone :-)

Code! Learn how to program with Swift