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

Kristopher Wood
seal-mask
.a{fill-rule:evenodd;}techdegree
Kristopher Wood
iOS Development Techdegree Student 5,552 Points

Lost on how to retrieve the value from the array

Would appreciate help on this one. Not sure how to finish this off and retrieve the value from the array. Thanks

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 {
  print("\(numbers) + \(numbers)")
  counter += 1
  }

  repeat {
    print ("sum = sum + numbers)
      counter += 1
      } while counter < 1

2 Answers

Alex Koumparos
seal-mask
.a{fill-rule:evenodd;}techdegree
Alex Koumparos
Python Development Techdegree Student 36,887 Points

Hi Kristopher,

First, you don't need any of the repeat block, so let's just delete that to get your plain while loop:

while counter < numbers.count {
  print("\(numbers) + \(numbers)")
  counter += 1
}

Now, we need to replace the print statement you have right now with code to perform the actions from the challenge:

1: "Using the value of counter as an index value, retrieve each value from the array"

So this means we need to access the values in numbers with counter. Accessing the values in an array was handled back in Introduction to Collections. Or if you want a text-based refresher on accessing arrays, you can look at Apple's (very readable) Swift Language Guide.

2: "add it to the value of sum"

Once we have the value from the array we just add that to the existing value. The challenge gives examples of syntax for doing this, either:

sum = sum + newValue

or

sum += newValue

Where newValue is the value you got from the array.

Hope this helps. If you're still stuck after revisiting the Introduction to Collections video and/or reading Apple's guide to arrays, let me know which bit you don't get and I'll give you some more pointers.

Cheers

Alex