The for-in loop allows you to iterate over any sequence.
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
let names = ["James", "Emily", "Miles"]
for name in names {
print(name)
}
// James
// Emily
// Miles
If you need the index for each element in the array, you can use the [enumerate()](<http://swiftdoc.org/v2.2/protocol/SequenceType/#func--enumerate>)
method on [SequenceType](<http://swiftdoc.org/v2.2/protocol/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 Int
s, 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.
In Swift 3, enumerate()
has been renamed to [enumerated()](<http://swiftdoc.org/v3.0/protocol/Sequence/#func--enumerated>)
:
for (index, name) in names.enumerated() {
print("The index of \\(name) is \\(index).")
}
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.
You can use the [reverse()](<http://swiftdoc.org/v2.2/protocol/SequenceType/#func--reverse>)
method on [SequenceType](<http://swiftdoc.org/v2.2/protocol/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
In Swift 3, reverse()
has been renamed to [reversed()](<http://swiftdoc.org/v3.0/protocol/Sequence/#func--reversed>)
:
for i in (0..<3).reversed() {
print(i)
}
By using the [stride(_:_:)](<http://swiftdoc.org/v2.2/protocol/Strideable/#func--stride-through_by_>)
methods on [Strideable](<http://swiftdoc.org/v2.2/protocol/Strideable/>)
you can iterate over a range with a custom stride: