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

Why does it have to say (numbers[index])

I wrote it correctly but I just want to understand more clearly, why do I HAVE to write [index] in the (numbers[index]) can someone explain why it has to be there? I just wan't to understand thoroughly why it must say index there. What does it mean?

My code:

let numbers = [1,2,3,4,5,6,7,8,9,10] var index = 0 while index < numbers.count{ println(numbers[index]) index ++ }

2 Answers

Olla Ashour
Olla Ashour
2,491 Points

Your basically try to access the value at a certain index in the array. Its like if you have a cargo in a cargo box, the cargo box is identified by a number, to get the contents you have to have the cargo box number. So its the same thing here, to get the value in the array, you need to access it using its index, and this index is in fact a pointer which points to a memory address of the value. And then to get the next index, you have to increment your current index by one, so the pointer will move to the next address. Hope this helped.

J.D. Sandifer
J.D. Sandifer
18,813 Points

It might also help to see what's happening behind the scenes at each step as the program goes through the while loop in your code:

// Step #     Index is     What the print function looks like on this step     Output
// 1          0            println(numbers[0])                                 1
// 2          1            println(numbers[1])                                 2
// 3          2            println(numbers[2])                                 3
// 4          3            println(numbers[3])                                 4
// all the way to...
// 10         9            println(numbers[9])                                 10
// and we exit the while loop. (because index becomes 10 on the next step and equals numbers.count)

Index is a variable to take the place of 0, 1, 2, etc. (the array indexes) so we can use a loop and add 1 to it each time rather than write out 10 println statements. Image how hard that would be if you had 100 numbers instead of just 10... Loops make our work so much easier!