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 Basics (retired) Control Flow While and Do-While Loop

I have absolutely no idea

What's the answer? I've sat at my computer for (I kid you not) seven hours.

while_loops.swift
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
while numebrs = [1...10] {
}

1 Answer

Chase Marchione
Chase Marchione
155,055 Points

Hi Conor,

1) We'll define our array of numbers (which you have.)

2) We'll create an index variable, which is our counter variable. Essentially, this variable will represent each index (the order of the item) in our numbers array. We'll update it (using the statement 'index++'... I discuss this in step 5) when our loop is ready to finish evaluating one of the array's items and is ready for the next array item.

3) The while loop will check that the index being operated on is less than the amount of items in the numbers array. The first item in an array is considered to be at the '0th' index, so the math works out (the while loop will eventually test the condition 'if 10 < 10'... since that condition will evaluate to false, the while loop will properly finish executing.)

4) We'll print to console the actual value (in this case, it'll be a number, since we have an array of numbers.) The syntax we're using for this is 'println(array[index])'. We are saying "Print the value that is stored in this index # of this array."

5) We'll increment the value of the index before the while loop goes back to its header and prepares for its next iteration. This way, we assure that the while loop will evaluate the next item in the array, rather than be stuck on the first item.

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

var index = 0
while index < numbers.count {
  println(numbers[index])
  index++
}

Hope this helps!