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

Code challenge with while loop in swift, confusion.

THIS IS MY CODE

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

while counter < numbers.count { print(counter) counter++ }

SOLUTION FOR THE CHALLENGE

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

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

}

so I was not even close to the solution but still want to understand three things; why the solution code does't use print ?, what is print ? , why is the code, inside the body of the while loop, telling the computer to do? in this steps "sum+=numbers" "[counter]"

Somebody can help noob guy here ? xD

4 Answers

Okay well first, print is basically just a way to test your code and see if something within a statement is running properly. In this particular example the while loop is telling the sum variable to increase by the returned indexed value of the array. The [counter] part is what tells the numbers array which index to return to then add to sum. As long as the counter variable which is being incremented is less than the number of items in the array, the array will return the value of counter as an indexed value. If I were to make an array of numbers lets say... let arrayOfNumbers = [1,2,3,4]. and I then wanted to return a value in that array.. lets say the number 2.. I would write arrayOfNumbers[1]. In this case 1 is "hard coded" while in your example it is a variable [counter] that is changing from the ++ operator. Hope that helps!

Could it be as simple as it's failed to run because your spelling of "counter' in your code initially was spelt "caunter", so when you refer to "counter" (spelt correctly) it isn't finding the variable?

thx, on other thing you are saying that print i just a way to test your code, but is to away to communicate something to the user ?

I could just tell you but really you should just go hop in Xcode and experiment with print and return. Keep chuggin along ??

the var caunter don't worry is just I had the code in playground and I already had var call counter but when I put in the challenge I made the correction.