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 For-In Loop

Jonathan Dueck
Jonathan Dueck
4,596 Points

A for-in loop is: "For Constant in Array {}". How can it be a constant if its value changes each time through the loop?

If

2 Answers

Vittorio Somaschini
Vittorio Somaschini
33,371 Points

Hello Jonathan.

Actually that word (the one that follows the word "for") can be anything you like.

The fact is that it creates a constant in that moment, when the loop executes, so that value is assigned to it.

Nothing changes, it gets executed n times depending on the things in the array.

Donald Gray II
Donald Gray II
5,341 Points

Another thing I noticed:

It seems as if the constant used for the loop is ephemeral. If you try to call its value after running the loop, an error results.

If you declare a variable or constant with the same name used for the constant in the for-in loop, you can do so without resulting with an error.

I'm no expert in Swift or in any other language for that matter, but I hope these observations help.