Swift Language For-in loop


Example

The for-in loop allows you to iterate over any sequence.

Iterating over a range

You can iterate over both half-open and closed ranges:

for i in 0..<3 {
    print(i)
}

for i in 0...2 {
    print(i)
}

// Both print:
// 0
// 1
// 2

Iterating over an array or set

let names = ["James", "Emily", "Miles"]

for name in names {
   print(name)
}

// James
// Emily
// Miles
2.12.2

If you need the index for each element in the array, you can use the enumerate() method on SequenceType.

for (index, name) in names.enumerate() {
   print("The index of \(name) is \(index).")
}

// The index of James is 0.
// The index of Emily is 1.
// The index of Miles is 2.

enumerate() returns a lazy sequence containing pairs of elements with consecutive Ints, starting from 0. Therefore with arrays, these numbers will correspond to the given index of each element – however this may not be the case with other kinds of collections.

3.0

In Swift 3, enumerate() has been renamed to enumerated():

for (index, name) in names.enumerated() {
   print("The index of \(name) is \(index).")
}

Iterating over a dictionary

let ages = ["James": 29, "Emily": 24]

for (name, age) in ages {
    print(name, "is", age, "years old.")
}

// Emily is 24 years old.
// James is 29 years old.

Iterating in reverse

2.12.2

You can use the reverse() method on SequenceType in order to iterate over any sequence in reverse:

for i in (0..<3).reverse() {
    print(i)
}

for i in (0...2).reverse() {
    print(i)
}

// Both print:
// 2
// 1
// 0

let names = ["James", "Emily", "Miles"]

for name in names.reverse() {
    print(name)
}

// Miles
// Emily
// James
3.0

In Swift 3, reverse() has been renamed to reversed():

for i in (0..<3).reversed() {
    print(i)
}

Iterating over ranges with custom stride

2.12.2

By using the stride(_:_:) methods on Strideable you can iterate over a range with a custom stride:

for i in 4.stride(to: 0, by: -2) {
    print(i)
}

// 4
// 2

for i in 4.stride(through: 0, by: -2) {
    print(i)
}

// 4
// 2
// 0
1.23.0

In Swift 3, the stride(_:_:) methods on Stridable have been replaced by the global stride(_:_:_:) functions:

for i in stride(from: 4, to: 0, by: -2) {
    print(i)
}

for i in stride(from: 4, through: 0, by: -2) {
    print(i)
}