SwiftUI Fatal error: Index out of range: file Swift/ContiguousArrayBuffer.swift

一世执手 提交于 2021-01-28 02:13:03

问题


I have a environment object that is an array, and a panel in my settings page where the user can add/remove values to the array...here is the list of items in the array displayed visually for the user:

ScrollView {
    VStack {
        ForEach(self.env.numbers.indices, id: \.self) { number in
            ZStack {
                HStack {
                    Text("#\(number +  1): ")
                        .font(Font.custom(K.font.montserratMedium, size: 17.0))
                        .foregroundColor(Color(K.SettingsTextColor))
                    
//                                            Spacer()
                    
                    NumberTextField(self.env.numbers[number], text: self.$env.numbers[number])
        
                }
                
                
                
            }
            
        }
    }
}

and at the bottom of my view is a toggle to change the number of items in the array:

Stepper(onIncrement: {
    
    self.env.numbers.append("12345")
    print("default number should be added")
    print(self.env.numbers.indices)
    print(self.env.numbers)
    print("count = \(self.env.numbers.count)")
    
},
        
        onDecrement: {
            
            if self.env.numbers.count != 0 {
                print("number should be removed")
                self.env.numbers.removeLast(1)
//              also tried self.env.numbers = self.env.numbers.droplast() but this didnt work
                print(self.env.numbers.indices)
                print(self.env.numbers)
                print("count = \(self.env.numbers.count)")
                
}

the NumberTextField view is a UIKit UITextField wrapper, and seems to work fine. Everything about this works fine until I try to decrease the stepper, and I get the Index out of range error (which surprisingly shows the error happening in the app delegate)...any ideas how to fix this?

来源:https://stackoverflow.com/questions/63383459/swiftui-fatal-error-index-out-of-range-file-swift-contiguousarraybuffer-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!