Index Out of Range in Swift with Removeatindex

Index out of range in Swift with removeAtIndex

You should not remove it from inside of the loop, when you call removeAtIndex(i) Array removes the item so you have 1 less item then countArray.. so you have to have another array to remember which item you want to remove and remove it outside of the loop.. or better option is to use filter

// Filter only strings that match stockSymbol
Array = Array.filter { $0 == stockSymbol! }

index out of range array error when removing an element in swift

Here I am giving you example what actually what you'r trying to do in you below code work

spawnLocations.remove(at: 0)
spawnLocations.remove(at: 2)
spawnLocations.remove(at: 4)

In your project, your array have four values

Index - > 0, 1, 2, 3

Now, you remove object at index : 0, -> spawnLocations.remove(at: 0)
So now your updated array have 3 values,

index -> 0, 1, 2

In next step, you remove index : 2 -> spawnLocations.remove(at: 2)

So updated array will be,

index -> 0, 1

Now in the same array you have 2 values at index 0 & 1 and your are tring to remove object at index : 4 -> spawnLocations.remove(at: 4)

Hope you get your mistake.

Solution

Reverse you order of removing array object

spawnLocations.remove(at: 4)
spawnLocations.remove(at: 2)
spawnLocations.remove(at: 0)

Removing from array - Fatal error: Index out of range - SwiftUI Binding

Removing with a pre given index is always a risk. Possibility of data changing in background etc. Get the index at the time you try to remove the item to be sure to have the right one. In case the data changed somewhere else.
This should help you understand:

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)"))
}

}
}

Produces this:

Sample Image

As you mentioned your error lies in the first view. This is most likely because you are building the ForEach with the number of indices. The moment you remove one, the ForEach runs into the error as it loses "track" of the item and the item with the index the ForEach provided does not exist anymore.
Try this:

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)

}

Index out of range when removing value from array

You are using an index of a different collection. Why would you expect both elements to be in the same index? What happens is that the two collection have different number of elements. First change the declaration of your savedArray. Don't use Any. Use the type of your element. Make your array type the same type as your title property. Then find the firstIndex of your element in your savedArray and remove it.

Your code should look something like this (if your title property is a String):

Array declaration:

var savedArray: [String] = []

Appending new elements:

self.savedArray.append(obj[indexPath.row].title)

Removing the element:

if let index = self.savedArray.firstIndex(of: obj[indexPath.row].title) {
self.savedArray.remove(at: index)
}

SwiftUI: Index out of range when last element gets removed

I found a solution, I changed my forEach to:

ForEach(checklistItems.indices, id: \.self) { index in
HStack {
RowView(
checklistItem:
Binding(
get: { self.checklistItems[index] },
set: { self.checklistItems[index] = $0 }
),
viewModel: viewModel
)
.padding(.leading, 12)

if checklistEditMode {
Button {
checklistItems.remove(at: index)
} label: {
Image("XCircle")
.resizable()
.frame(width: 18, height: 18)
}
.padding(.trailing, 12)
}
}
.padding(.horizontal, 12)
.padding(.top, 12)
.padding(.bottom, 4)

Divider()
.frame(width: 311)
}

and it works now with no crashes, Thanks to this

Thread 1: Fatal error: Index out of range when removing from array with @Binding

In your code the ForEach with indicies and id: \.self is a mistake. The ForEach View in SwiftUI isn’t like a traditional for loop. The documentation of ForEach states:

/// It's important that the `id` of a data element doesn't change, unless
/// SwiftUI considers the data element to have been replaced with a new data
/// element that has a new identity.

This means we cannot use indices, enumerated or a new Array in the ForEach. The ForEach must be on the actual array of identifiable items. This is so SwiftUI can track the row Views moving around, which is called structural identity and you can learn about it in Demystify SwiftUI WWDC 2021.

So you have to change your code to something this:

import SwiftUI

struct Item: Identifiable {
let id = UUID()
var num: Int
}

struct IntView: View {

let num: Int

var body: some View {
Text("\(num)")
}
}

struct ArrayView: View {

@State var array: [Item] = [Item(num:0), Item(num:1), Item(num:2)]

var body: some View {
ForEach(array) { item in
IntView(num: item.num)

Button(action: {
if let index = array.firstIndex(where: { $0.id == item.id }) {
array.remoteAt(index)
}
}, label: {
Text("remove")
})

}
}
}

iOS Swift : fatal error: Index out of range

Your index value is based on arr3. As you remove items from arr2 that index doesn't represent the proper location in arr2.

One solution is to iterate arr3 in reverse.

for (index, element) in arr3.enumerated().reversed() {

This keeps the remaining indexes the same as the iteration continues.



Related Topics



Leave a reply



Submit