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()
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 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()
:
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()
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
In Swift 3, reverse()
has been renamed to reversed()
:
for i in (0..<3).reversed() {
print(i)
}
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
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)
}