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

A for-in-loop Constant

I see that this question has been asked multiple times and yet I still dont understand. In Amits example he uses a constant within a For in loop, why does he do this when the loop will bring out a new result each time it executes or am I misunderstanding.

Thanks

Faizal

1 Answer

Stone Preston
Stone Preston
42,016 Points

the following is an excerpt from the Swift eBook:

for index in 1...5 {
    println("\(index) times 5 is \(index * 5)")
}

In the example above, index is a constant whose value is automatically set at the start of each iteration of the loop. As such, it does not have to be declared before it is used. It is implicitly declared simply by its inclusion in the loop declaration, without the need for a let declaration keyword.

so while yes the value inside the parenthesis is a constant, its value gets automatically set at each iteration of the loop. its kind of a special case constant in a way, since its value does changes during each iteration.