在SwiftUI中使用带ForEach的枚举

在SwiftUI中使用带ForEach的枚举,swift,swiftui,Swift,Swiftui,我想知道使用enumerated withForEach的语法。我使用的是customID 这是我的密码: ForEach(arrayNew.enumerated(), id:\.customID) { (index, item) in } 更新: ForEach(Array(arrayNew.enumerated()), id:\.element.customID) { (index, item) in Text(String(index) + item) } 假设我们有一个

我想知道使用enumerated with
ForEach
的语法。我使用的是
customID

这是我的密码:

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

}
更新:

ForEach(Array(arrayNew.enumerated()), id:\.element.customID) { (index, item) in
    Text(String(index) + 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")
]
现在,如果我们想从数组中访问
偏移量
,我们需要使用
枚举()

但是,它返回一个
枚举序列
(而不是
数组
):

这里的问题是,
EnumeratedSequence
不符合
RandomAccessCollection

但是
Array
可以-我们只需要将
enumerated()
的结果转换回
Array

@inlinable public func enumerated() -> EnumeratedSequence<Array<Element>>
Array(arrayNew.enumerated())
现在,我们可以在
ForEach
中直接使用它:

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

这回答了你的问题吗?还是这个?非常感谢,我不明白为什么我要把我的arrayNew放到另一个数组中?为什么?另外,请参阅我的更新以了解任何改进,这有助于理解为什么我必须使用Array(),但为什么我们在这里不需要它:**for(index,item)in.enumerated(){}***mimi这是因为
for in
循环要求符合
序列
——这适用于
数组
枚举序列
。in循环的标准
与SwiftUI
ForEach
完全不同。非常有用,再次感谢!最后一个问题是,当我们在代码中使用enumerated()时,是否会在应用程序中产生副作用?使用枚举方法运行代码会很昂贵吗?我的意思是,如果我只使用我的代码而不进行枚举,它在运行时会更快吗?@mimi据我所知,你应该看不到任何区别。
Array(arrayNew.enumerated())
ForEach(Array(arrayNew.enumerated()), id: \.element.customID) { offset, item in
    Text("\(offset) \(item.customID) \(item.value)")
}