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 2.0 Collections and Control Flow Control Flow With Loops For In Loop

Why is the loop creating a constant named task if task is treated like a variable?

At the 5:50 mark of the video, Pasan begins describing how the for loop performs it's magic. It creates a placeholder named task in this case and for every iteration of the loop, the contents of task gets changed. In reality, task should be a variable since it's contents are changed frequently, no? In the video he uses the let keyword.

1 Answer

Dalisson Figueiredo
Dalisson Figueiredo
7,731 Points

No, "task" is actually a local constant that is declared by the for loop over and over again so it can receive multiple values, think like this, by the end of each iteration the "task" constant is freed so it can be declared again with another value. If you want more on this try running the following code:

let toDo = ["program", "watch Okuribito", "sleep", "finish the salmon of doubt book"]

for task in toDo{
    task = "verifying if task is a constant"  //Line of test, this line shall point you an error.

You will see that the line of test, when you try to change the value of the local constant "task", will give you an error and the code won't run, because the value of task can't be changed in the middle of the loop, by the end of the loop the "task" constant will be terminated and declared again with the value of the next string in the array.