从数组中删除 - 致命错误:索引超出范围 - SwiftUI 绑定

JSK*_*JSK 5 ios swiftui

我正在尝试了解 SwiftUI 绑定。在这里,我在视图中显示一个数组并将值绑定到第二个视图。在第二个视图中,我从数组中删除数据。

但是我得到以下信息,

致命错误:索引超出范围

我没有收到错误,因为self.person.notes.remove(at: self.index)事实上这实际上是删除数组中的注释。使用时它必须在第一个视图中,ForEach因为数组已被修改,现在它超出了范围。但我不确定如何解决这个问题?当然Binding应该已经解决了这个问题。

查看1

ForEach(self.person.notes.indices, id:\.self) { index in

   NoteView(person: self.$person, room: self.$home.notes[index], index: index)

}
Run Code Online (Sandbox Code Playgroud)

查看2

@Binding var person: Person
@Binding var note: Note
var index: Int

if self.index > 0 {
       Button(action: {
             self.person.notes.remove(at: self.index)
       }) {
           Text("Remove")
       }
 }
Run Code Online (Sandbox Code Playgroud)

知道这在 SwiftUI 中应该如何工作吗?

Sim*_*mon 2

使用预先给定的索引删除始终存在风险。数据在后台更改的可能性等。在尝试删除项目时获取索引,以确保拥有正确的项目。万一数据在其他地方发生了变化。这应该可以帮助您理解:

struct ContentView: View {
    
    @State var myData: Array<String> = ["first", "second", "third"]
    
    var body: some View {
        ForEach(self.myData, id: \.self) { data in
            SecondView(myData: self.$myData, data: data)
        }
    }
}

struct SecondView: View {
    
    @Binding var myData: Array<String>
    // the data that is being tied to the view
    var data: String
    
    var body: some View {
        
        Button(action: {
            // calculate the index at the time of removal
            if let index = self.myData.firstIndex(of: self.data) {
                self.myData.remove(at: index)
            }
        }) {
            Rectangle().foregroundColor(Color.red).frame(width: 100, height: 100).overlay(Text("Button \(self.data)"))
        }
        
    }
}

Run Code Online (Sandbox Code Playgroud)

产生这个:

在此输入图像描述

正如您提到的,您的错误在于第一个视图。这很可能是因为您正在使用索引数量构建 ForEach。当您删除一个项目时,ForEach 就会遇到错误,因为它失去了该项目的“跟踪”,并且具有 ForEach 提供的索引的项目不再存在。尝试这个:

ForEach(self.person.notes, id:\.self) { note in

   // Remove the index and calculate it on the second view as shown above. This then should solve the problem
   NoteView(person: self.$person, room: self.$home.notes)

}
Run Code Online (Sandbox Code Playgroud)