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

Patrick Anderson
Patrick Anderson
2,826 Points

What am I don't incorrectly???

My solution of the second task isn't working. I'm not sure why the code isn't working when it works in Xcode.

while.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(counter);
counter++}
while counter < numbers.count { print(sum+=numbers[counter]);
counter++}

2 Answers

Ben Shockley
Ben Shockley
6,094 Points

You're code is fine, although you don't need two while loops going there. The problem is just with your syntax. Sometimes the compiler on the website requires a stricter syntax than what Xcode requires.

If you put a space between the variables and the += operation then it should pass. So it would look like this.

while counter < numbers.count { print(sum += numbers[counter]);
counter++}

-- Ben

Patrick Anderson
Patrick Anderson
2,826 Points

I added the space and it still didn't work......This is very frustrating!!

Patrick Anderson
Patrick Anderson
2,826 Points

Ah!! I finally erased the other loop first!! While, this is a lesson for me not to try to learn code while Im sleepy. Thanks for all your help!!

Greg Kaleka
Greg Kaleka
39,021 Points

Hi Patrick,

So you've got everything right, except that for the second challenge, you needed to change your code, rather than add onto it. The reason is, by the time you get to the second while loop, the counter is already equal to numbers.count, so nothing happens!

All you have to do to fix it is delete your first while loop.

I will also make a case for well-formatted code. It's somewhat hard to read your code as you've formatted it. To format it better, just put a new line after the opening curly brace, and before the closing brace, and indent your code properly. You also don't need semicolons in Swift (although they're not technically wrong, you should follow convention and not use them.

formatting.swift
while counter < numbers.count {
    print(sum += numbers[counter])
    counter++
}

Cheers :beers:

-Greg