SwiftUI List crashes when removing a selected item

389 views Asked by At

I have a severe problem with the SwiftUI List view in Xcode 12 (beta) (MacOS App).

When a List item, which is selected, is removed, the List crashes every time.

"[General] Row 2 out of row range [0-1] for rowViewAtRow:createIfNeeded:"

Looks like a bug in SwiftUI to me. What can I do to prevent the crash? I've tried several things already, but with no success.

Example code:

//
// Example to reproduce bug
// * Select no item or other than last item and press button: selection is reset, last item is removed, no crash
// * Select last list item and press button "Delete last item" => Crash
//

import SwiftUI

class MyContent: ObservableObject {
    @Published var items: [String] = []
    @Published var selection: Set<String> = Set()
    
    init() {
        for i in 1...5 {
            self.items.append(String(i))
        }
    }
}

struct MyView: View {
    @ObservedObject var content: MyContent = MyContent()
    
    var body: some View {
        VStack {
            List(content.items, id: \.self, selection: $content.selection) {
                item in
                Text("\(item)")
            }
            
            Button("Delete last item", action: {
                if content.items.count > 0 {
                    content.selection = Set()  // reset selection
                    var newItems = Array(content.items)
                    newItems.removeLast()
                    content.items = newItems
                }
            })
        }
    }
}
1

There are 1 answers

0
ikemuc On BEST ANSWER

Re-tested after installing MacOS 11.0 Beta 7 (20A5374g). The example code doesn’t crash any more, the bug seems to be fixed.

Thanks to all for testing and so giving me the hint, that it's a MacOS beta bug. :-)