Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.5k views
in Technique[技术] by (71.8m points)

swift - SwiftUI out of index when deleting an array element in ForEach

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...