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 Collections and Control Flow Control Flow With Loops While and Repeat While

Confused about the second part of while loops

I do not under stand what were doing or what this bit of code does

var index = 0 while index < todo.count

does this code talk to the line of code earlier with the todo array we did in a few videos back or is this something different? I am also confused about what a index does here?

is there any where I can get a second example of this?

1 Answer

Cory Harkins
Cory Harkins
16,500 Points

Hmmm.

var index = 0

Our todo array (or ANY array) is "zero indexed" meaning we identify EACH value within an array with a numerical ID starting from 0.

var anyArray = [value with an index of 0, value with an index of 1, value with an index of 2]

So now, we want to print the values of our array or access all of them somehow.

We can use a while loop to do this. Let's say the array we're given has over 100+ values stored inside! Instead of counting or knowing before hand, we can use anyArray.count OR (todo.count) to find the total length of the array.

To loop through anything you need a range, because INDEXes in arrays start at 0, we make a variable to ID that index start point: ie; var index = 0 //the starting point for todo

THEN we need a max range, which will be the total length of the array

todo.count

We can also store that into a variable as well for easy management

var lengthOfArray = todo.count

Now we have a base range (index = 0) and a max range (lengthOfArray) we can say

//while index is less than lengthOfArray { do something then increase the value of index }

while index < lengthOfArray { print(todo[index]) index = index + 1
//we don't want to print the same thing everytime, //so after the first index value is printed, //we need to increase the value of index to get the next value in the array }