简体   繁体   English

SwiftUI - 致命错误:从数组中删除元素时索引超出范围

[英]SwiftUI - Fatal error: index out of range on deleting element from an array

I have an array on appstorage.我在应用存储上有一个数组。 I'm displaying its elements with foreach method.我正在使用 foreach 方法显示其元素。 It has swipe to delete on each element of the array.它可以在数组的每个元素上滑动删除。 But when i delete one, app is crashing.但是当我删除一个时,应用程序崩溃了。 Here is my first view;这是我的第一个观点;

struct View1: View {

    @Binding var storedElements: [myElements]
    
    var body: some View{
        GeometryReader {
            geometry in
        
        VStack{
            ForEach(storedElements.indices, id: \.self){i in
                View2(storedElements: $storedElements[i], pic: $storedWElements[i].pic, allElements: $storedElements, index: i)
                }
        }.frame(width: geometry.size.width, height: geometry.size.height / 2, alignment: .top).padding(.top, 25)
        }
    }
    
}

And View 2;和视图2;

struct View2: View {
    
    @Binding var storedElements: myElements
    @Binding var pic: String
    @Binding var allElements: [myElements]
    var index: Int
    
    @State var offset: CGFloat = 0.0
    @State var isSwiped: Bool = false
    
    @AppStorage("pics", store: UserDefaults(suiteName: "group.com.some.id"))
    var arrayData: Data = Data()
    
    var body : some View {
            ZStack{
                
                Color.red
                
                HStack{
                    Spacer()
                    
                    Button(action: {
                        withAnimation(.easeIn){
                            delete()}}) {
                        Image(systemName: "trash").font(.title).foregroundColor(.white).frame(width: 90, height: 50)
                    }
                }
                View3(storedElements: $storedElements).background(Color.red).contentShape(Rectangle()).offset(x: self.offset).gesture(DragGesture().onChanged(onChanged(value:)).onEnded(onEnd(value:)))
            }.frame(width: 300, height: 175).cornerRadius(30)
        }
    }
    func onChanged(value: DragGesture.Value) {
        
        if value.translation.width < 0 {
            
            if self.isSwiped {
                self.offset = value.translation.width - 90
            }else {
                self.offset = value.translation.width
            }
        }
    }
    func onEnd(value: DragGesture.Value) {
        
        withAnimation(.easeOut) {
            if value.translation.width < 0 {
                if -value.translation.width > UIScreen.main.bounds.width / 2 {
                    self.offset = -100
                    delete()
                }else if -self.offset > 50 {
                    self.isSwiped = true
                    self.offset = -90
                }else {
                    self.isSwiped = false
                    self.offset = 0
                }
            }else {
                self.isSwiped = false
                self.offset = 0
            }
        }
    }
    
    func delete() {
        //self.allElements.remove(at: self.index)
        if let index = self.allElements.firstIndex(of: storedElements)  {
            self.allElements.remove(at: index)
        }
    }
}

OnChange and onEnd functions are for swiping. OnChange 和 onEnd 函数用于滑动。 I think its the foreach method that is causing crash.我认为它是导致崩溃的 foreach 方法。 Also tried the commented line on delete function but no help.还尝试了删除 function 的注释行,但没有帮助。 And I know its a long code for a question.而且我知道它是一个很长的问题代码。 I'm trying for days and tried every answer here but none of them solved my problem here.我尝试了几天并在这里尝试了所有答案,但没有一个能解决我的问题。

In your myElements class/struct, ensure it has a unique property.在您的 myElements 类/结构中,确保它具有唯一的属性。 If not add one and upon init set a unique ID如果没有添加一个并在初始化时设置一个唯一的 ID

public class myElements {
  var uuid: String
  
  init() {
      self.uuid = NSUUID().uuidString
  }
}

Then when deleting the element, instead of然后在删除元素时,而不是

if let index = self.allElements.firstIndex(of: storedElements)  {
    self.allElements.remove(at: index)
}

Use利用

self.allElements.removeAll(where: { a in a.uuid == storedElements.uuid })

This is array bound safe as it does not use an index这是数组绑定安全的,因为它不使用索引

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 SwiftUI NavigationLink @绑定数组元素导致致命错误:索引超出范围 - SwiftUI NavigationLink @Binding of an array element causes Fatal error: Index out of range SwiftUI - 从数组中删除项目导致致命错误:索引超出范围 - SwiftUI - Removing Item from Array causes Fatal Error: Index out of Range 线程 1:致命错误:索引超出范围 In SwiftUI - Thread 1: Fatal error: Index out of range In SwiftUI 致命错误:SwiftUI 中的索引超出范围 - Fatal error: Index out of range in SwiftUI Swift:致命错误:从TableView删除项目时数组索引超出范围 - Swift: fatal error: Array index out of range on deleting item from a tableview 通过从阵列崩溃中删除项目并出现致命错误来删除tableView中的项目:索引超出范围 - Deleting item in tableView by removing item from array crashes with fatal error: Index out of range Swift致命错误:插入元素时数组索引超出范围 - Swift Fatal error: Array index is out of range when inserting an element SwiftUI 为没有显式索引的应用程序添加元素时抛出“致命错误:索引超出范围” - SwiftUI throwing 'Fatal error: Index out of range' when adding element for app with no explicit indexing 从UICollection删除项目但出现“数组索引超出范围”错误 - Deleting items from a UICollection but getting an “Array index out of range” error 快速致命错误:数组索引超出范围 - Swift fatal error: Array index out of range
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM