Call enumerated() and unpack the pair: for (i, item) in items.enumerated() { … }. i counts from 0. To loop backwards, use items.reversed() or stride(from: 10, through: 0, by: -1), and to map with an index, chain items.enumerated().map { … }. On a slice or a String, the count from enumerated() is not a valid index: use zip(items.indices, items) there.
Swift's for-in loop hands you the elements, not their positions, and the C-style for (i = 0; i < n; i++) loop is gone from the language. You get the position back in one of three ways: enumerated() counts for you, indices gives the collection's own index values, and a range such as 0..<n or stride counts on its own. The sections below cover each one, the slice trap where a count and an index differ, looping in reverse, and map, filter and reduce with an index, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.
1enumerated()Recommended
enumerated() turns any sequence into a sequence of pairs. Each pair is a tuple with two named parts, offset (a counter that starts at 0) and element, and the loop can unpack it into two names. It needs no import and works on arrays, sets, strings, ranges and anything else you can loop over. For numbering that people read, add 1 when you print, or zip the items with the one-sided range 1....
let fruits = ["apple", "banana", "cherry"] // enumerated() yields (offset, element) pairs, counting from 0 for (index, fruit) in fruits.enumerated() { print("\(index): \(fruit)") } // Numbering for people: add 1 when you print for (i, fruit) in fruits.enumerated() { print("\(i + 1). \(fruit)") } // Or pair the items with an open range that starts at 1 for (n, fruit) in zip(1..., fruits) { print("#\(n) \(fruit)") } // Keep the tuple whole and read .offset and .element for pair in fruits.enumerated() where pair.offset > 0 { print(pair.offset, pair.element) }
Output
The first loop prints 0: apple to 2: cherry; adding 1 gives 1. apple to 3. cherry, and zip(1..., fruits) prints the same numbers without the arithmetic. The open range never runs out, because zip stops at the shorter of its two sequences. A where clause filters on the pair, so the last loop skips offset 0 and prints 1 banana and 2 cherry.
2indices and zip: real indices
The number enumerated() gives you is a count from 0, not an index into the collection. On an Array the two happen to match. They don't on an ArraySlice: scores[2...] keeps the indices of the array it came from, so its first element is at index 2. When you need an index to subscript with, loop over indices, or zip the indices with the elements to get both. Looping over indices is also how you change an array's elements in place.
var scores = [10, 20, 30, 40, 50] // indices is the range of valid positions print(scores.indices) // Change elements in place through their index for i in scores.indices { scores[i] += i } print(scores) // A slice keeps the indices of the array it came from let tail = scores[2...] print("tail.indices:", tail.indices) // enumerated() still counts from 0: offsets, not indices for (offset, value) in tail.enumerated() { print("offset \(offset) -> \(value)") } // zip(indices, collection) pairs each element with its real index for (i, value) in zip(tail.indices, tail) { print("tail[\(i)] = \(value)") } // A String is indexed by String.Index, not Int let word = "hello" for (i, ch) in zip(word.indices, word) where ch == "l" { print("l found, rest is", word[i...]) }
Output
scores.indices prints 0..<5, and adding each index to its element gives [10, 21, 32, 43, 54]. The slice tells the story: tail.indices: 2..<5, yet enumerated() reports offsets 0, 1 and 2. Writing tail[offset] with those offsets crashes on the first pass with Fatal error: Index out of bounds, because tail[0] does not exist. The zip loop prints the real indices, tail[2] = 32 to tail[4] = 54. For a String, word[i] with an Int doesn't even compile (cannot subscript String with an Int, use a String.Index instead.), so zip with word.indices to get a String.Index you can slice with: llo and lo. More on that in getting a substring.
3Counting loops: ranges and stride
When the loop is about numbers rather than an array, loop over a range. 0..<n is half-open and leaves n out, which is what you want for positions; 1...n is closed and includes the end. For a step other than 1, use stride(from:to:by:), which stops before the end, or stride(from:through:by:), which may land on it. Both work with Double too. If you don't use the counter, name it _.
// Half-open range: 0, 1, 2 (3 is left out) for i in 0..<3 { print("i =", i) } // A range is a sequence, so Array() shows what a loop visits print(Array(1...5)) // stride(from:to:by:) stops before the end; through: can reach it print(Array(stride(from: 0, to: 9, by: 3))) print(Array(stride(from: 0, through: 9, by: 3))) print(Array(stride(from: 0.0, through: 1.0, by: 0.25))) // Every other element, by index let colors = ["red", "green", "blue", "cyan", "pink"] for i in stride(from: 0, to: colors.count, by: 2) { print(i, colors[i]) } // 0..<count is empty for an empty array: the loop just doesn't run let none: [String] = [] for i in 0..<none.count { print("never printed", i) } // No use for the counter? Name it _ var bar = "" for _ in 0..<4 { bar += "#" } print(bar)
Output
0..<3 visits 0, 1 and 2, while 1...5 includes 5. The two strides differ only at the end: to: 9 gives [0, 3, 6] and through: 9 gives [0, 3, 6, 9]. Stepping by 2 over colors.count picks red, blue and pink. Prefer 0..<items.count over 0...items.count - 1: on an empty array the first is an empty range, but the second is 0...-1, which crashes with Fatal error: Range requires lowerBound <= upperBound. And when the range is 0..<items.count anyway, items.indices says the same thing more clearly.
4Looping in reverse order
reversed() walks an array back to front. On an array it returns a lightweight view rather than a copy, so it costs nothing extra. A range reverses the same way, (0..<n).reversed(), and stride with a negative step counts down. What you can't write is 10...0: a range must go upward. With enumerated(), the order of the two calls decides which numbers you get.
let letters = ["a", "b", "c"] // reversed() walks the array back to front for letter in letters.reversed() { print(letter) } // Counting down: reverse a range, or stride with a negative step for i in (0..<3).reversed() { print("i =", i) } print(Array(stride(from: 10, through: 0, by: -5))) // Original positions, last to first for (i, letter) in letters.enumerated().reversed() { print("\(i): \(letter)") } // Fresh count over the reversed order for (i, letter) in letters.reversed().enumerated() { print("\(i): \(letter)") }
Output
reversed() prints c, b, a, and the reversed range counts i = 2 down to i = 0. stride(from: 10, through: 0, by: -5) gives [10, 5, 0]; it is the closest match to the old for (i = 10; i >= 0; i -= 5). The last two loops show the difference: enumerated().reversed() keeps each letter's original position (2: c first), while reversed().enumerated() numbers the reversed order from 0 (0: c first). Writing for i in 3...0 compiles, but crashes at run time with Fatal error: Range requires lowerBound <= upperBound.
5map, filter and reduce with an index
map and reduce don't pass an index, but they don't need to: call them on enumerated() and each element arrives as an (offset, element) pair. Read it as $0.offset and $0.element, or unpack it into two names in the closure. When the "index" is really a second array, zip the two arrays instead of indexing one with the other.
let names = ["Ana", "Ben", "Cy", "Dee"] // map with the offset and the element let numbered = names.enumerated().map { "\($0.offset + 1). \($0.element)" } print(numbered) // The closure can unpack the pair into two names let tagged = names.enumerated().map { i, name in "\(name)#\(i)" } print(tagged) // filter by position, then drop the offsets again let everyOther = names.enumerated() .filter { $0.offset.isMultiple(of: 2) } .map(\.element) print(everyOther) // reduce: add at even positions, subtract at odd ones let values = [5, 3, 8, 1] let alternating = values.enumerated().reduce(0) { total, pair in pair.offset.isMultiple(of: 2) ? total + pair.element : total - pair.element } print(alternating) // Two arrays side by side: zip stops at the shorter one let prices = [2.5, 4.0, 1.25] let counts = [2, 1, 4, 99] let total = zip(prices, counts).map { $0 * Double($1) }.reduce(0, +) print(total)
Output
map builds ["1. Ana", "2. Ben", …], and unpacking the pair as i, name reads more clearly once the closure grows. Filtering on offset and mapping back with the key path \.element keeps positions 0 and 2: ["Ana", "Cy"]. The alternating sum is 5 - 3 + 8 - 1 = 9. The zip total is 14.0: the fourth count, 99, has no price and is ignored, so check the lengths yourself when a mismatch is a bug.
6Which should you use?
| Method | Gives you | Best for |
|---|---|---|
| for (i, x) in xs.enumerated() | Count from 0 + element | Most loops: numbering, printing, positions in an array |
| for (i, x) in zip(xs.indices, xs) | Real index + element | Slices, strings, any index you will subscript with |
| for i in xs.indices | Real index | Changing elements in place: xs[i] = … |
| for i in 0..<n / stride | Numbers only | Counting loops, steps other than 1 |
| xs.reversed() | Elements, back to front | Reverse order without copying |
| xs.enumerated().map { … } | A new array | map, filter, reduce that need the position |
Frequently asked questions
Does Swift have a C-style for loop?
No. for var i = 0; i < 3; i += 1 no longer compiles; the compiler says C-style for statement was removed in Swift 3. Use for i in 0..<3 for a counting loop, stride(from:to:by:) for other steps, and enumerated() or indices when you loop over a collection.
How do I make enumerated() start at 1?
enumerated() always counts from 0 and has no start parameter. Add 1 where you use it (print("\(i + 1). \(item)")), or pair the items with an open range: for (n, item) in zip(1..., items) gives 1, 2, 3 and stops when the items run out.
Is the offset from enumerated() the same as the index?
Only when the collection's indices start at 0 and go up by 1, as they do for an Array. An ArraySlice such as scores[2...] starts at index 2, so subscripting it with an offset crashes with Fatal error: Index out of bounds, and a String is indexed by String.Index, not Int. Use zip(xs.indices, xs) when you need an index to subscript with.
How do I loop from 10 down to 0 in Swift?
Use for i in stride(from: 10, through: 0, by: -1) or for i in (0...10).reversed(). Writing for i in 10...0 compiles but crashes at run time with Fatal error: Range requires lowerBound <= upperBound, because a range must go upward.
How do I get the index in forEach or map?
Call them on enumerated(): items.enumerated().forEach { print($0.offset, $0.element) } or items.enumerated().map { i, item in … }. Each element is an (offset, element) tuple. A plain for (i, item) in items.enumerated() loop is usually easier to read than forEach, and it supports break and continue.
How do I change array elements while looping with an index?
Loop over the indices and assign through the subscript: for i in scores.indices { scores[i] += i }. The array must be a var. The item in for item in scores is a copy and a let: item += 1 fails with 'item' is a 'let' constant, and it would not change the array anyway.