【问题标题】:Unable to use ForEach loop on @Binding variable [closed]无法在@Binding 变量上使用 ForEach 循环[关闭]
【发布时间】:2021-04-29 12:49:55
【问题描述】:

我最近问了一个问题,但它被删除了,因为他们认为答案已经存在,所以我查看了这个question。我已尝试将此处找到的解决方案实施到我的代码中,但现在遇到了一个稍微不同的错误。

基本上,我正在尝试创建一个简单的应用程序,其中包含可以单击以导航到具有编辑功能的详细信息视图的项目列表。数据是从 JSON 文件中读取的,这就是数据位于绑定中的原因,因此可以对其进行更新,这在项目的其他任何地方都不是问题。


import SwiftUI

struct EateryList: View {
    @Binding var eateries: [Eatery]
    var body: some View {
        NavigationView {
            VStack {
                List {
                    ForEach(eateries.indicies, id: \.self) { i in
                            NavigationLink(destination: EateryDetail(eatery: $eateries[i])) { //errors appear here
                               EateryRow(eatery: $eateries[i])
                           }
                        }
                }
                .navigationTitle("Favourite Eateries")
                .navigationBarItems(leading: EditButton(), trailing: Button( action: add)
                {
                    Image(systemName: "plus")
                    
                }
                    )
                     .listStyle(InsetGroupedListStyle())
            }
        }
        
    }
    func add() {
        eateries.append(Eatery(name: "Eatery", location: "Insert location here", notes: "Insert notes here", reviews: ["Insert reviews here"], url: "https://i.imgur.com/y3MMnba.png"))
    }
}

我目前收到 3 个我不完全理解的代码错误...

通用结构 'ForEach' 要求 'Binding' 符合 'RandomAccessCollection'

引用下标 'subscript(dynamicMember:)' 需要包装器 'Binding'

“[Eatery]”类型的值没有使用根类型“[Eatery]”的键路径的动态成员“indicies”

现在非常感谢所有帮助,如果您需要进一步澄清项目的其他部分,请告诉我:)

【问题讨论】:

    标签: swift foreach swiftui binding


    【解决方案1】:

    这是一个拼写错误。是indices 不是indicies

    ForEach(eateries.indices, id: \.self) { i in //<-- Here
        NavigationLink(destination: EateryDetail(eatery: $eateries[i])) { 
            EateryRow(eatery: $eateries[i])
        }
    }
    

    【讨论】:

    • 男孩,这之后我觉得自己很傻吗...
    • 由错字引起的问题使问题脱离主题。您应该投票结束问题,并留下评论来解释错字,而不是回答问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-06
    • 1970-01-01
    • 2012-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多