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 If Statement

How does it know that "card" is one of the numbers in the range of constant "cards"?

Where is it declared that "card" is one of the numbers in the range? We haven't specified what "card" is so I'm confused... It's as if this has just been pulled from the air with no connection...

2 Answers

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

It sounds like your talking about the for loop in one of the array challenges, right? Something like this?:

let cards = 1...13

for card in cards {
    //other code here
}

If that's what you're looking at, I understand your confusion. It does seem almost magical how the variable appears out of thin air.

It turns out the for loop defines the card variable for us. It's almost like it's writing var card = cards[0], going through the loop, and then writing var card = cards[1], going through the loop again, etc. up to cards[12] - the last item in the array. We just get to use one convenient statement to achieve all of those effects.

Since it's a variable like any other, we can also use it in the loop. If it helps, remember card could be any correct variable name - like loopCounter or i.

this also confused me. it's not pointed out in the video that "card" doesn't need to be initialized.