在 SwiftUI 中使用 ForEach 枚举 [英] Using enumerated with ForEach in SwiftUI

查看:41
本文介绍了在 SwiftUI 中使用 ForEach 枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道使用 ForEach 枚举的语法.我正在使用 customID.

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

这是我的代码:

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

}

更新:

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

推荐答案

假设我们有一个 Array 类型的对象,Item:

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

现在,如果我们想从数组中访问 offset item,我们需要使用 enumerated():

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

arrayNew.enumerated()

然而,它返回一个EnumeratedSequence(并且不是一个Array):

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

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

如果我们看一下ForEach的签名,我们可以看到它期望RandomAccessCollection:

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

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

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

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

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

Array(arrayNew.enumerated())

现在,我们可以直接在ForEach中使用它:

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

这篇关于在 SwiftUI 中使用 ForEach 枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆