Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI out of index when deleting an array element in ForEach

Tags:

swift

swiftui

I looked through different questions here, but unfortunately I couldn't find an answer. This is my code:

SceneDelegate.swift

...
let contentView = ContentView(elementHolder: ElementHolder(elements: ["abc", "cde", "efg"]))
...
window.rootViewController = UIHostingController(rootView: contentView)

ContentView.swift

class ElementHolder: ObservableObject {

    @Published var elements: [String]

    init(elements: [String]) {
        self.elements = elements
    }
}

struct ContentView: View {

    @ObservedObject var elementHolder: ElementHolder

    var body: some View {
        VStack {

            ForEach(self.elementHolder.elements.indices, id: \.self) { index in
                SecondView(elementHolder: self.elementHolder, index: index)
            }

        }
    }
}

struct SecondView: View {

    @ObservedObject var elementHolder: ElementHolder
    var index: Int

    var body: some View {
        HStack {
            TextField("...", text: self.$elementHolder.elements[self.index])
            Button(action: {
                self.elementHolder.elements.remove(at: self.index)
            }) {
                Text("delete")
            }
        }
    }

}

When pressing on the delete button, the app is crashing with a Index out of bounds error.

There are two strange things, the app is running when

1) you remove the VStack and just put the ForEach into the body of the ContentView.swift or

2) you put the code of the SecondView directly to the ForEach

Just one thing: I really need to have the ObservableObject, this code is just a simplification of another code.

UPDATE

I updated my code and changed Text to a TextField, because I cannot pass just a string, I need a connection in both directions.

like image 937
Lupurus Avatar asked Apr 25 '20 19:04

Lupurus


2 Answers

The issue arises from the order in which updates are performed when clicking the delete button.

On button press, the following will happen:

  1. The elements property of the element holder is changed
  2. This sends a notification through the objectWillChange publisher that is part of the ElementHolder and that is declared by the ObservableObject protocol.
  3. The views, that are subscribed to this publisher receive a message and will update their content.
    1. The SecondView receives the notification and updates its view by executing the body getter.
    2. The ContentView receives the notification and updates its view by executing the body getter.

To have the code not crash, 3.1 would have to be executed after 3.2. Though it is (to my knowledge) not possible to control this order.

The most elegant solution would be to create an onDelete closure in the SecondView, which would be passed as an argument.

This would also solve the architectural anti-pattern that the element view has access to all elements, not only the one it is showing.

Integrating all of this would result in the following code:

struct ContentView: View {
    @ObservedObject var elementHolder: ElementHolder

    var body: some View {
        VStack {
            ForEach(self.elementHolder.elements.indices, id: \.self) { index in
                SecondView(
                    element: self.elementHolder.elements[index],
                    onDelete: {self.elementHolder.elements.remove(at: index)}
                )
            }
        }
    }
}

struct SecondView: View {
    var element: String
    var onDelete: () -> ()

    var body: some View {
        HStack {
            Text(element)
            Button(action: onDelete) {
                Text("delete")
            }
        }
    }
}

With this, it would even be possible to remove ElementHolder and just have a @State var elements: [String] variable.

like image 74
Palle Avatar answered Nov 15 '22 08:11

Palle


Here is possible solution - make body of SecondView undependable of ObservableObject.

Tested with Xcode 11.4 / iOS 13.4 - no crash

struct SecondView: View {

    @ObservedObject var elementHolder: ElementHolder
    var index: Int
    let value: String

    init(elementHolder: ElementHolder, index: Int) {
        self.elementHolder = elementHolder
        self.index = index
        self.value = elementHolder.elements[index]
    }

    var body: some View {
        HStack {
            Text(value)     // not refreshed on delete
            Button(action: {
                self.elementHolder.elements.remove(at: self.index)
            }) {
                Text("delete")
            }
        }
    }
}

Another possible solution is do not observe ElementHolder in SecondView... for presenting and deleting it is not needed - also no crash

struct SecondView: View {

    var elementHolder: ElementHolder // just reference
    var index: Int

    var body: some View {
        HStack {
            Text(self.elementHolder.elements[self.index])
            Button(action: {
                self.elementHolder.elements.remove(at: self.index)
            }) {
                Text("delete")
            }
        }
    }
}

Update: variant of SecondView for text field (only changed is text field itself)

struct SecondViewA: View {

    var elementHolder: ElementHolder
    var index: Int

    var body: some View {
        HStack {
            TextField("", text: Binding(get: { self.elementHolder.elements[self.index] },
                set: { self.elementHolder.elements[self.index] = $0 } ))
            Button(action: {
                self.elementHolder.elements.remove(at: self.index)
            }) {
                Text("delete")
            }
        }
    }
}
like image 30
Asperi Avatar answered Nov 15 '22 09:11

Asperi