Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Swift Functions and Optionals Optionals What is an Optional?

Optional question

in the if statement, he says tempAptNumber in aptNumbers {

if (tempAptNUmber in aptNumbers){ return aptNumber } }

why does he not declare the tempAptNumber again? how does the system know what tempAptNumber is?

1 Answer

Marissa Amaya
Marissa Amaya
11,782 Points

Hello. I gave an in-depth answer to this question here. But more to your point, recall how a for-in loop works:

for data in data_array {
    //do something
}

"data_array" can be any iterable data structure. For the purposes of this course, it's an array. The array is already declared before he calls the for-in loop. So, what the for-in loop does automatically is the following:

for loop 1. the program automatically assigns "data" to the first value in the array

var data = data_array[0]
//"data" can now be used in the rest of the loop

for loop 2. the program automatically assigns "data' to the second value in the array

var data = data_array[1]
//"data" can now be used in the rest of the loop

And so on, until there are no more values left in the array. That is when the loop finishes, and the program continues.