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

Liam Hayes
seal-mask
.a{fill-rule:evenodd;}techdegree
Liam Hayes
Full Stack JavaScript Techdegree Student 13,116 Points

Question about for in loops and arrays

Hey guys, you know how you have to create your own constant in a for in loop? Like this:

for someConstant in myArray{}

What is that constant? Is it the index number or is it the element or is it both?

Here's some examples of what I mean:

This:

var anArray: [Int] = [2,3,4,5]

for someConstant in anArray{
    print(someConstant)
}

prints out this: 2 3 4 5 (so I assume someConstant is the element)

And this:

var anArray: [Int] = [2,3,4,5]

for someConstant in anArray{
    anArray.insert(someConstant + 1, at: someConstant)
    print(anArray[someConstant])
}

prints out this: 3 4 5 6 (which I think would mean that someConstant is the index number)

Thank you for the help guys :)

1 Answer

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there! That constant is not the index, but rather the name of an individual item currently being looked at in an array. Let's take this example (it might be easier with strings):

var fruitBasket: [String] = ["banana", "pear", "apple", "lemon"]

for fruit in fruitBasket{
    print(fruit)
}

The first time through the loop, "banana" will be assigned to the variable fruit, The second time through the loop, "pear" will be assigned to the variable fruit. This will continue in this manner until all elements have been read in this way or until something that would break the loop is encountered (such as a break or return statement).

Hope this helps! :sparkles: