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

Jake White
Jake White
2,108 Points

What am I doing wrong?

I can't get the second part of this question.

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

// Enter your code below
while  counter < 0 {
    print(6)
    counter++
}
var index < 0
repeat {
    print(numbers)
    counter++
} while counter < 0

2 Answers

I hope you're trying these in Swift playgrounds because it helps a lot.

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

// Enter your code below

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

print(numbers) // [2, 8, 1, 16, 4, 3, 9]
print(counter) // 7
print(sum) // 43

++ is deprecated so you should use += 1

Note: You could also use this later on when you get more comfortable with Swift.

recursive.swift
let multiples = [2,8,1,16,4,3,9]
var sum = multiples.reduce(0, combine: +)

print(sum)  // 43

reduce just means reduce a collection of elements down to a single value by combining them.

You could also do some neat stuff like this.

recursive.swift
let numbersArray = [2,8,1,16,4,3,9]
var runningTotal = 0

for (index, numbers) in numbersArray.enumerate() {  // this is now enumerated() in Swift 3
    runningTotal += numbersArray[index]
    print(runningTotal) // 2, 10, 11, 27, 31, 34, 43
}
Jake White
Jake White
2,108 Points

Awesome thank you very much this was very helpful, I really appreciate the help!

Jack Weller
Jack Weller
6,404 Points

Hey, you want to add the value from the index number "counter" from the array "numbers". We can do this by writing sum += numbers[counter]

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

// Enter your code below

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