How to iterate a loop with index and element in Swift How to iterate a loop with index and element in Swift arrays arrays

How to iterate a loop with index and element in Swift


Yes. As of Swift 3.0, if you need the index for each element along with its value, you can use the enumerated() method to iterate over the array. It returns a sequence of pairs composed of the index and the value for each item in the array. For example:

for (index, element) in list.enumerated() {  print("Item \(index): \(element)")}

Before Swift 3.0 and after Swift 2.0, the function was called enumerate():

for (index, element) in list.enumerate() {    print("Item \(index): \(element)")}

Prior to Swift 2.0, enumerate was a global function.

for (index, element) in enumerate(list) {    println("Item \(index): \(element)")}


Swift 5 provides a method called enumerated() for Array. enumerated() has the following declaration:

func enumerated() -> EnumeratedSequence<Array<Element>>

Returns a sequence of pairs (n, x), where n represents a consecutive integer starting at zero and x represents an element of the sequence.


In the simplest cases, you may use enumerated() with a for loop. For example:

let list = ["Car", "Bike", "Plane", "Boat"]for (index, element) in list.enumerated() {    print(index, ":", element)}/*prints:0 : Car1 : Bike2 : Plane3 : Boat*/

Note however that you're not limited to use enumerated() with a for loop. In fact, if you plan to use enumerated() with a for loop for something similar to the following code, you're doing it wrong:

let list = [Int](1...5)var arrayOfTuples = [(Int, Int)]()for (index, element) in list.enumerated() {    arrayOfTuples += [(index, element)]}print(arrayOfTuples) // prints [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]

A swiftier way to do this is:

let list = [Int](1...5)let arrayOfTuples = Array(list.enumerated())print(arrayOfTuples) // prints [(offset: 0, element: 1), (offset: 1, element: 2), (offset: 2, element: 3), (offset: 3, element: 4), (offset: 4, element: 5)]

As an alternative, you may also use enumerated() with map:

let list = [Int](1...5)let arrayOfDictionaries = list.enumerated().map { (a, b) in return [a : b] }print(arrayOfDictionaries) // prints [[0: 1], [1: 2], [2: 3], [3: 4], [4: 5]]

Moreover, although it has some limitations, forEach can be a good replacement to a for loop:

let list = [Int](1...5)list.reversed().enumerated().forEach { print($0, ":", $1) }/*prints:0 : 51 : 42 : 33 : 24 : 1*/

By using enumerated() and makeIterator(), you can even iterate manually on your Array. For example:

import UIKitimport PlaygroundSupportclass ViewController: UIViewController {    var generator = ["Car", "Bike", "Plane", "Boat"].enumerated().makeIterator()    override func viewDidLoad() {        super.viewDidLoad()        let button = UIButton(type: .system)        button.setTitle("Tap", for: .normal)        button.frame = CGRect(x: 100, y: 100, width: 100, height: 100)        button.addTarget(self, action: #selector(iterate(_:)), for: .touchUpInside)        view.addSubview(button)    }    @objc func iterate(_ sender: UIButton) {        let tuple = generator.next()        print(String(describing: tuple))    }}PlaygroundPage.current.liveView = ViewController()/* Optional((offset: 0, element: "Car")) Optional((offset: 1, element: "Bike")) Optional((offset: 2, element: "Plane")) Optional((offset: 3, element: "Boat")) nil nil nil */


Starting with Swift 2, the enumerate function needs to be called on the collection like so:

for (index, element) in list.enumerate() {    print("Item \(index): \(element)")}