Blog / May 28, 2022 / 2 mins read / By Mahi Garg

Enumerated in Swift

Enumerated is used to iterate over a collection along with the position access. It returns a sequence of Pairs where the first element in the Pair is the index and the second element is the element itself of the collection.

Enumerated is useful when we want to access the position along with making any iteration, filtration or even mapping of the objects of a collection.

Lets look at its definition first.

/* Returns a sequence of pairs (*n*, *x*), 
where *n* represents a consecutive integer starting at zero 
and *x* represents an element of the sequence. */
@inlinable public func enumerated() -> EnumeratedSequence<Array<Element>>

Enumerated best use case is with an array.

let array = [1, 2, 3, 4, 5]
for (index, item) in array.enumerated() {
    print("Item at \(index) is \(item)")
}

It can also be used with set and map but the order of insertion is not guaranteed in both set and map.

let set = [1, 2, 3, 4, 5]
for (index, item) in set.enumerated() {
    print("Item at \(index) is \(item)")
}
let map = [1: "One", 2: "Two", 3: "Three"]
for (index, item) in map.enumerated() {
    print("Item at \(index) is key: \(item.key) value: \(item.value)")
}

Enumerated can also be used to iterate over a string with the sequence of Pairs of the index and the respective character at that index.

for (index, item) in "Swift".enumerated() {
    print("Item at \(index) is \(item)")
}
//this will print
Item at 0 is S
Item at 1 is w
Item at 2 is i
Item at 3 is f
Item at 4 is t

There is no need to convert the string to a char array first and then iterate over it. The Enumerated function will take care of it.

Comments