SwiftUI List: changing section order + changing item = app crash

Originator:huan.xiong
Number:rdar://FB9952691 Date Originated:Mar 10, 2022
Status:Open Resolved:
Product:iOS Product Version:15.3
Classification: Reproducible:always
 
Run the code below. Press the button once (or twice at most) is almost certain to crash the app. 

The app shows a list containing two sections, each of which have four items. When button is pressed, it inserts a new item into each section and also changes the section order.

import SwiftUI

let groupNames = (1...2).map { "\($0)" }
let groupNumber = groupNames.count

let itemValues = (1...4)
let itemNumber = itemValues.count

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

struct Group: Identifiable {
    var name: String
    var items: [Item]
    var id = UUID()
    
    // insert a random item to the group
    mutating func insertItem() {
        let index = (0..<itemNumber).randomElement()!
        items.insert(Item(value: 100), at: index)
    }
}

struct Data {
    var groups: [Group]

    // initial data: 2 sections, each having 4 items.
    init() {
        groups = groupNames.map { name in
            let items = itemValues.map{ Item(value: $0) }
            return Group(name: name, items: items)
        }
    }
    
    // multiple changes: 1) reverse group order 2) insert a random item to each group
    mutating func change() {
        groups.reverse()
        for index in groups.indices {
            groups[index].insertItem()
        }
    }
}

struct ContentView: View {
    @State var data = Data()
    
    var body: some View {
        VStack {
            List {
                ForEach(data.groups) { group in
                    Section {
                        ForEach(group.items) { item in
                            Text("\(group.name): \(item.value)")
                        }
                    }
                header: {
                        Text("Section \(group.name)")
                    }
                }
            }
            Button("Press to crash the app!") {
                withAnimation {
                    data.change()
                }
            }
            .padding()
        }
    }
}

Comments


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!