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 Basics (retired) Control Flow For-In Loop

Collin Keating
Collin Keating
1,797 Points

for in loops

I just have no understanding on how for-in loops work... Is there any great examples you could provide for me so I can grasp the idea of them just a little bit better!?

for_loops.swift
for number in 1...10{
println("\(number)\(number*7)")
}

1 Answer

Hayden Pennington
Hayden Pennington
6,154 Points

The for-in loop, is just a convienent way to loop a particular number of times. While also creating a variable of the current index.

// This for-in loop will loop 10 times.
// The first time through, number will be 0.
// The second iteration, number will be 1.
// And so on. The last time through, number will be 9
for number in 0...9 {
    println(number)
}

// It is the same as this standard for-loop
for var number = 0; number <= 9; number++ {
    println(number)
}

// My favorite use, for the for-in, is when I want to iterate through an array, to print, edit, //compare etc. And I need a variable containing the current element.

// So, you have an array of names, and you want to print each name.
var names = ["John", "Adam", "Bill", "Dave"]


// You can cleanly iterate, and print each name
for aName in names {
    println(aName)
}

// That same code with a standard for-loop, would look like this;
for var index = 0; index < names.count; index++ {
    let aName = names[index]
    println(aName)
}
Collin Keating
Collin Keating
1,797 Points

Thank you very much! It truly was a huge help