For details, see Swift Evolution - Remove C style for-loops
To quote the reasoning:
- Both
for-in
and stride
provide equivalent behavior using Swift-coherent approaches without being tied to legacy terminology.
- There is a distinct expressive disadvantage in using for-loops compared to for-in in succinctness
for-loop
implementations do not lend themselves to use with collections and other core Swift types.
- The
for-loop
encourages use of unary incrementors and decrementors, which will be soon removed from the language.
- The semi-colon delimited declaration offers a steep learning curve from users arriving from non C-like languages
- If the for-loop did not exist, I doubt it would be considered for inclusion in Swift 3.
In summary: there are better ways (more expressive) than a C-style for-loop
to iterate in Swift.
Some examples:
for-in
over a range:
for i in 0 ..< 10 {
//iterate over 0..9
print("Index: \(i)")
}
for i in (0 ..< 10).reverse() {
//iterate over 9..0
print("Index: \(i)")
}
For arrays (and other sequences) we have many options (the following is not a complete list):
let array = ["item1", "item2", "item3"]
array.forEach {
// iterate over items
print("Item: \($0)")
}
array.reverse().forEach {
// iterate over items in reverse order
print("Item: \($0)")
}
array.enumerate().forEach {
// iterate over items with indices
print("Item: \($1) at index \($0)")
}
array.enumerate().reverse().forEach {
// iterate over items with indices in reverse order
print("Item: \($1) at index \($0)")
}
for index in array.indices {
// iterate using a list of indices
let item = array[index]
print("Item \(item) at index: \(index)")
}
Also note that if you are converting an array to another array, almost always you want to use array.filter
or array.map
or a combination of them.
For all Strideable
types we can use the stride
method to generate indices, for example:
for index in 10.stride(to: 30, by: 5) {
// 10, 15, 20, 25 (not 30)
print("Index: \(index)")
}
for index in 10.stride(through: 30, by: 5) {
// 10, 15, 20, 25, 30
print("Index: \(index)")
}
With arrays we can do:
for index in 0.stride(to: array.count, by: 2) {
// prints only every second item
let item = array[index]
print("Item \(item) at index: \(index)")
}