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

How was value assigned

In this example, how was number automatically assigned a value?

for number in 1...10 { print("(number) times 5 is equal to (number * 5)")}

1 Answer

andren
andren
28,558 Points

The way a for loop works is that it takes an array or range and then pulls out each individual item from that and assigns it to a variable you define.

In the example you post number is the variable that the loop uses to store the individual item and 1...10 is a range of numbers.

So during the first loop number is assigned the first item of the 1...10 range which is the number 1, then during the second loop number is assigned the second item in the 1...10 range which is the number 2, and so on. It continues like that until it has gone though all of the numbers in that range and then it stops looping.

So to answer your question more directly, number is assigned a value by the for loop itself. That is a fundamental part of how for loops work. for loops makes it really easy to run some block of code on a list of values. Let's say you had an array of names for example and wanted to print a greeting for each of the names, that could be done as simply as this:

let names = ["James", "Tom", "Maria", "Erica"]

for name in names {
    print("Good day \(name).")
}

That would print:

Good day James.
Good day Tom.
Good day Maria.
Good day Erica.

Thank you. It's clear now.