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

Mahmoud Rajabzadeh-Mashhadi
Mahmoud Rajabzadeh-Mashhadi
489 Points

While

What does "increment count variable" mean? Thanks.

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

// Enter your code below
while counter < 1 {
print ("counter")
}

2 Answers

A correct solution for this challenge is this...

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++
}
Jason Anders
MOD
Jason Anders
Treehouse Moderator 145,860 Points

Hey there Mahmoud. Welcome to Treehouse.

There are a couple issues with you code for this challenge.

  • First, the challenge wants the while loop to run as long as the counter is less that the length of the array. So where you have "while counter < 1", you'll need to change the 1 to be the length of the array using the count method.
while counter < numbers.count {
  • Second, the challenge does not ask you print anything, so that line needs to be deleted. Instead, you will need to increment the counter... which brings us to your question: If you don't increment the counter variable, the loop will run forever and the app/computer will crash. After each loop iteration, you will need to add 1 to the counter, so eventually the counter will no longer be less then the length of the array. This is accomplished a few ways, but the most common would be counter++.

Once all this is done, the final code for Task 1 will look like:

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

Hope this helps and makes sense. Keep Coding! :)