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

Lukas Muller
Lukas Muller
7,347 Points

What's 'task' doing in this example?

for task in todo { print(task) }

Can anyone explain what task or whatever you take does? I don't exactly get its use. And what do you call it? Is it a variable?

3 Answers

task is a variable. It's only available within the scope of the the for loop (meaning, that task won't exist outside of for ... { }.

for task in todo {
  print(task)
}

Your code says: Loop through todo array (start with the first item), and assign its value to task, then print task.

Although, you'll probably won't write code like this, the above for loop is effectively doing this:

var index = 0
while index < todo.count {
    let task = todo[index]
    print(task)
    index++
}
Lukas Muller
Lukas Muller
7,347 Points

Thanks! Now it makes more sense. The second code block is what I have learnt in the episode afterwards, but I wanted to understand the for-loop in this case too.

you can put anything you want instead of task just remember to update it in you print()

Lukas, in the end, it doesn't really matter how you call this thing. In its essence this is just a running index number of how many iterations you want to be executed by the for-loop. The syntax basically is:

for blaaaa in todo {
      print(todo[blaaaa])
}

People like to give this blaaaa a name, but in fact it doesnt matter. The only thing it does, is to be used as a placeholder in the todo-subscript (whats in square brackets [] after the arrayname) to advise the loop that it shall output the index number of the array.

James Estrada
seal-mask
.a{fill-rule:evenodd;}techdegree
James Estrada
Full Stack JavaScript Techdegree Student 25,866 Points

Your print statement will give the error: "cannot subscript a value of type '[String]' with an index of type 'String'". The statement inside the body should be: print(blaaa). What the correct for loop is doing is retrieving each item that is in "todo" one by one, assign it to the constant "blaaa" and print each one until there are no more items inside "todo"