Using enumerated with ForEach in SwiftUI

Viewed 987

I want to know about syntax of using enumerated with ForEach. I am using a customID.

Here is my code:

ForEach(arrayNew.enumerated(), id:\.customID) { (index, item) in

}

Update:

ForEach(Array(arrayNew.enumerated()), id:\.element.customID) { (index, item) in
    Text(String(index) + item)  
}
1 Answers

Let's assume we have an Array of objects of type Item:

struct Item {
    let customID: Int
    let value: String
}

let arrayNew = [
    Item(customID: 1, value: "1"),
    Item(customID: 23, value: "12"),
    Item(customID: 2, value: "32")
]

Now, if we want to access both offset and item from the array, we need to use enumerated():

arrayNew.enumerated()

However, it returns an EnumeratedSequence (and not an Array):

@inlinable public func enumerated() -> EnumeratedSequence<Array<Element>>

If we take a look at the signature of ForEach, we can see that it expects RandomAccessCollection:

public struct ForEach<Data, ID, Content> where Data : RandomAccessCollection, ID : Hashable

The problem here is that EnumeratedSequence doesn't conform to RandomAccessCollection.

But Array does - we just need to convert the result of enumerated() back to an Array:

Array(arrayNew.enumerated())

Now, we can use it directly in the ForEach:

ForEach(Array(arrayNew.enumerated()), id: \.element.customID) { offset, item in
    Text("\(offset) \(item.customID) \(item.value)")
}
Related