Got "Fatal error: Index out of range" : show index in list item for swiftui

Got "Fatal error: Index out of range" : show index in list item for swiftui

已更新:错误:类型“_”没有成员“1”,如果在 list-foreach 中放置一个 if 闭包(if !self.showMarkedOnly || name.marked {}),为什么?

代码版本 4:

struct Name: Identifiable, Hashable {
    var id: String = UUID().uuidString
    var name: String
    var marked: Bool
    init(_ name: String, marked: Bool = false) { self.name = name; self.marked = marked }
}

struct TestView: View {
    @State private var list: [Name] = [Name("test1"), Name("test2"), Name("test3", marked: true), Name("test4"), Name("test5", marked: true), Name("test6"), Name("test7"), Name("test8")]
    @State private var showMarkedOnly = false

    var body: some View {
        VStack{
            Toggle(isOn: $showMarkedOnly) { Text("show marked only") }
            List {
                ForEach(Array(zip(0..., list)), id: \.1.id) { index, name in
//                    if !self.showMarkedOnly || name.marked {
                        HStack {
                            Text("\(index)").foregroundColor(name.marked ? .red : .gray)
                            Spacer()
                            Text("\(name.name)")
                        }
                        .background(Color.gray.opacity(0.001))
                        .onTapGesture {
                            self.list.remove(at: index)
                        }
//                    }
                }
            }
        }
    }
}

=========

已更新:我发现代码版本 2 的问题,我必须为 ForEach 提供一个 id。并且更新了代码版本 2。

我找到了一种优雅的方式来显示索引,它避免了 self.list[index]。但是我发现在一些复杂的代码中出现错误"Type '_' has no member '1'"。

代码版本 3:

var body: some View {
        List {
            ForEach(Array(zip(0..., list)), id: \.1.id) { index, name in // a error occurs in some complex code: "Type '_' has no member '1'"
                HStack {
                    Text("\(index)")
                    Spacer()
                    Text("\(name.name)")
                }
                .background(Color.gray.opacity(0.001))
                .onTapGesture {
                    self.list.remove(at: index)
                }
            }
        }
    }

我显示一个列表,然后删除我点击的项目。它是代码版本 1,工作正常。 当我使用索引(代码 veriosn 2)将索引添加到列表项时,点击后得到 "Fatal error: Index out of range"。

代码版本 1:

struct Name: Identifiable, Hashable {
    var id: String = UUID().uuidString
    var name: String
    init(_ name: String) { self.name = name }
}

struct TestView: View {
    @State private var list: [Name] = [Name("test1"), Name("test2"), Name("test3"), Name("test4"), Name("test5"), Name("test6"), Name("test7"), Name("test8")]

    var body: some View {
        List {
            ForEach(list) { name in
                HStack {
                    Text("\(0)")
                    Spacer()
                    Text("\(name.name)")
                }
                .background(Color.gray.opacity(0.001))
                .onTapGesture {
                    self.list = self.list.filter { [=12=] != name }
                }
            }
        }
    }
}

代码版本 2:

struct TestView: View {
    @State private var list: [Name] = [Name("test1"), Name("test2"), Name("test3"), Name("test4"), Name("test5"), Name("test6"), Name("test7"), Name("test8")]

    var body: some View {
        List {
            //ForEach(list.indices) { index in
            ForEach(list.indices, id: \.self) { index in
                HStack {
                    Text("\(index)")
                    Spacer()
                    Text("\(self.list[index].name)")
                }
                .background(Color.gray.opacity(0.001))
                .onTapGesture {
                    self.list.remove(at: index)
                }
            }
        }
    }
}

这是因为 SwiftUI 会根据提供的原始数据重新加载其内容。 您可以通过修改

来解决它
ForEach(list) { item in
    HStack {
        Text("\(item.id)")
        Spacer()
        Text("\(item.name)")
    }
    .onTapGesture {
        guard let itemIndex = self.list.firstIndex(of: item) else { return }
        self.list.remove(at:itemIndex)
    }
}

否则,您可以使用内置的.onDelete()方法解决您的问题(通过滑动删除项目):

var body: some View {
    List {
        ForEach(list) { item in
            HStack {
                Text("\(item.id)")
                Spacer()
                Text("\(item.name)")
            }
            .background(Color.gray.opacity(0.001))
        }.onDelete(perform: delete)
    }
}

func delete(at offsets: IndexSet) {
    list.remove(atOffsets: offsets)
}

因为indices不是你的状态,数组才是。因此,您更新了数组,但 @State 实际上不够智能,无法更新它包装的值的计算属性或下游属性。如果您想要索引,请将其设为 ForEach:

中的标识符来源
ForEach(0..<list.count, id: \.self) {
    // the rest should be ok here
}

@State 是 属性 包装器,它将强制定义它的视图重新计算其 body.

在您的情况下,如果您删除索引处的项目,

HStack {
    Text("\(index)")
    Spacer()
    Text("\(self.list[index].name)")
}
.background(Color.gray.opacity(0.001))
.onTapGesture {
     self.list.remove(at: index)
 }

HStack 中的文本

Text("\(self.list[index].name)")

崩溃,只是因为list[index]不存在了。

正在使用

ForEach(list.indices, id:\.self) { index in ... }

而不是

ForEach(list.indices) { index in ... }

将强制 SwiftUI 重新创建 TestView(参见 ForEach 构造函数中的 id:\.self)

SwiftUI 将制作新的 TestView 副本,同时使用包装在@State 属性 包装器中的 属性 的新值。

更新

请不要更新你的问题...

您的最后一个代码版本 4 完全是一团糟,所以我将其重写为您可以复制的内容 - 粘贴 - 运行

import SwiftUI

struct Name: Identifiable, Hashable {
    var id: String = UUID().uuidString
    var name: String
    var marked: Bool
    init(_ name: String, marked: Bool = false) { self.name = name; self.marked = marked }
}

struct ContentView: View {
    @State private var list: [Name] = [Name("test1"), Name("test2"), Name("test3", marked: true), Name("test4"), Name("test5", marked: true), Name("test6"), Name("test7"), Name("test8")]
    @State private var showMarkedOnly = false

    var body: some View {
        VStack{
            Toggle(isOn: $showMarkedOnly) {
                Text("show marked only")
            }.padding(.horizontal)
            List {
                ForEach(Array(zip(0..., list)).filter({!self.showMarkedOnly || [=14=].1.marked}), id: \.1.id) { index, name in
                    HStack {
                        Text("\(index)").foregroundColor(name.marked ? .red : .gray)
                        Spacer()
                        Text("\(name.name)")
                    }
                    .background(Color.gray.opacity(0.001))
                    .onTapGesture {
                        self.list.remove(at: index)
                    }
                }
            }
        }
    }
}
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

它应该看起来像

根据讨论更新

ForEach 不同版本的构造函数在内部使用不同的 ViewBuilder 功能

@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
extension ViewBuilder {

    /// Provides support for "if" statements in multi-statement closures, producing an `Optional` view
    /// that is visible only when the `if` condition evaluates `true`.
    public static func buildIf<Content>(_ content: Content?) -> Content? where Content : View

    /// Provides support for "if" statements in multi-statement closures, producing
    /// ConditionalContent for the "then" branch.
    public static func buildEither<TrueContent, FalseContent>(first: TrueContent) -> _ConditionalContent<TrueContent, FalseContent> where TrueContent : View, FalseContent : View

    /// Provides support for "if-else" statements in multi-statement closures, producing
    /// ConditionalContent for the "else" branch.
    public static func buildEither<TrueContent, FalseContent>(second: FalseContent) -> _ConditionalContent<TrueContent, FalseContent> where TrueContent : View, FalseContent : View
}

这是关于 "implementation details" 的,希望它会在下一个版本中记录下来。 SwiftUI 仍处于非常早期的开发阶段,我们必须小心。

让我们尝试强制 SwiftUI 走我们自己的路! 先单独RowView

struct RowView: View {
    var showMarkedOnly: Bool
    var index: Int
    var name: Name
    //@ViewBuilder
    var body: some View {
        if !self.showMarkedOnly || name.marked {
            HStack {
                Text(verbatim: index.description).foregroundColor(name.marked ? .red : .gray)
                Spacer()
                Text(verbatim: name.name)
            }
            .background(Color.gray.opacity(0.001))

        }
    }
}

编译器抱怨

Function declares an opaque return type, but has no return statements in its body from which to infer an underlying type

取消注释以包裹我们的 body

struct RowView: View {
    var showMarkedOnly: Bool
    var index: Int
    var name: Name
    @ViewBuilder
    var body: some View {
        if !self.showMarkedOnly || name.marked {
            HStack {
                Text(verbatim: index.description).foregroundColor(name.marked ? .red : .gray)
                Spacer()
                Text(verbatim: name.name)
            }
            .background(Color.gray.opacity(0.001))

        }
    }
}

现在我们可以按照您喜欢的方式使用代码了:-)

struct ContentView: View {
    @State private var list: [Name] = [Name("test1"), Name("test2"), Name("test3", marked: true), Name("test4"), Name("test5", marked: true), Name("test6"), Name("test7"), Name("test8")]
    @State private var showMarkedOnly = false

    var body: some View {
        VStack{
            Toggle(isOn: $showMarkedOnly) {
                Text("show marked only")
            }.padding(.horizontal)
            List {
                ForEach(Array(zip(0..., list)), id: \.1.id) { (index, name) in
                    RowView(showMarkedOnly: self.showMarkedOnly, index: index, name: name).onTapGesture {
                    self.list.remove(at: index)
                }
                }
            }
        }
    }
}

最终结果使用现在 buildIf<Content> 构造并且所有代码再次运行(结果看起来与上面显示的完全相同)