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 trialBryan Moed
Courses Plus Student 451 Pointsfor ... in (meaning)
when you put in the playground
let card = 1...13
for card in cards { switch card{
what is the card ( that comes after the "for") and the cards (that comes after the (in") mean? what are they referring to ?
3 Answers
Stone Preston
42,016 Pointsa for in loop loops over all the values in an array and makes the item accessible in a local variable.
so with
for card in cards
the card variable is the item in the array, and cards is the array. you can then do something to every single card through the use of the card variable
for example, if I had an array of animals called animals, and wanted to loop over every single animal in that array and print it I would use
for animal in animals {
println(animal)
}
and every item in that array would get printed.
the name you give to the variable that comes after for does not really matter, it can be anything you want. Most of the time you have an array that stores a collection of things, so usually the variable is just the singular form of that thing
for thing in things {}
for rabbit in rabbits{}
but it can be any valid variable name
for asdf in things {}
for blah in rabbits{}
Abdurahman Sharif
1,205 Pointswow that was really helpful.thanks stone!!
Michael Pastran
4,727 PointsThanks!! really helps clear stuff up
Omar Nunez
4,101 Pointscard is a variable included in the array cards is a array constant(let)
in your first line you should refer to cards and no card (Β¨let card = 1...13Β¨) and it will be more clear.
Bryan Moed
Courses Plus Student 451 PointsBryan Moed
Courses Plus Student 451 Pointsthanks that helped me understand it a lot better!