Using enumerated with ForEach in SwiftUI

时光总嘲笑我的痴心妄想 提交于 2021-01-28 08:52:11

问题


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:


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)")
}


来源:https://stackoverflow.com/questions/65512565/using-enumerated-with-foreach-in-swiftui

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!