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
jurgen meco
30 Pointswhat does "for" mean in swift language?
please help
2 Answers
Nikhil Bukowski
2,981 Points'for', as in probably every language, is used to loop through code multiple times. Swift supports this action in two ways.
In Swift, like in Python, you can use for-in loops. These will loop through a code block once for each item in an ordered collection. These are written as follows:
for item in collection {
//code to be looped over
}
For example,
for index in [1, 2, 3, 4, 5] {
print("This has now printed \(index) time(s)."
}
//This has now been printed 1 time(s).
//This has now been printed 2 time(s).
//This has now been printed 3 time(s).
//This has now been printed 4 time(s).
//This has now been printed 5 time(s).
You can also use the more common form of the for loop, which contains an initialization, a condition, and an increment. The initialization runs when the for loop starts. The increment runs at the end of the code block to be looped over (before checking the condition). The condition is checked at the end of the code block to be looped over and if the condition is true, then the code runs from the beginning of code block. In general, a for loop looks like this:
for initialization; condition; increment {
//code to be looped over
}
And, for a specific example:
for var index = 1; index<6; ++index {
print("This has now printed \(index) time(s)."
}
//This has now been printed 1 time(s).
//This has now been printed 2 time(s).
//This has now been printed 3 time(s).
//This has now been printed 4 time(s).
//This has now been printed 5 time(s).
Hope this helps.
jurgen meco
30 Pointsok thanks :D