Thursday, November 3, 2022
HomeiOS Developmentios - SwiftUI Index Out of Vary Crash When Clearing Array

ios – SwiftUI Index Out of Vary Crash When Clearing Array


On iOS 15, utilizing SwiftUI, if I set a @Printed var to a brand new occasion of an object, which has array properties, any views utilizing ForEach(merchandise) { $merchandise .... (the place merchandise conforms to Identifiable and merchandise is an array var) crashes with SwiftUI.swift: line 635 Index Out of Vary when the brand new occasion is ready, i.e. the array gadgets are eliminated. The identical happens if I simply set self.object.merchandise = []

let’s imagine I’ve the next setup:

class ExampleClass: ObservableObject {

    static let shared: ExampleClass = ExampleClass()

    @Printed var exampleItem: CustomStructure = CustomStructure(param_1: "", param_2: "")

    personal init() {
    }

    func clearExampleItem() {
        DispatchQueue.primary.async {
            self.exampleItem = CustomStructure(param_1: "", param_2: "") // Reset exampleItem clearing all arrays
        }
    }

    struct CustomStructure {
        var customArray: [CustomItem] = []

        init() {
            self.customArray = []
            let customArray: [CustomItem] = []
            for index in 0..<100 {
                let newCustomItem = CustomItem(index: index)
                customArray.append(newCustomItem)
            }
            self.customArray = customArray
        }

        struct CustomItem: Identifiable {
            var id: Int {
                self.index
            }
            var index: Int
            var moreItems: [MoreItem] = [MoreItem(index: 1), MoreItem(index: 2)]
        }
        struct MoreItem: Identifiable {
            var id: Int {
                self.index
            }
            var index: Int
        }
    }
}

And in a SwiftUIView:

import SwiftUI

struct exampleView: View {

    @StateObject var exampleClass: ExampleClass = ExampleClass.shared

    var physique: some View {
        VStack {
            ForEach(self.$exampleClass.exampleItem.customArray) { $customItem in
                ExampleSubView(exampleClass: self.exampleClass, customItem: $customItem)
            }
        }
    }
}

struct ExampleSubView: View {
    @ObservedObject var exampleClass: ExampleClass
    @Binding var customItem: ExampleClass.CustomItem

    var physique: some View {
        HStack {
            ForEach(self.customItem.moreItems) { moreItem in
                Button(motion: {
                    self.exampleClass.clearExampleItem()
                }) {
                    Textual content("(moreItem.index)")
                }
            }
        }
    }
}

As soon as ExampleClass.clearExampleItem() is named, I get the Index Out of Vary crash from SwiftUI. This does not appear to occur on iOS 16.

Any assist a lot appreciated.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments