ios – SwiftUI Index Out of Vary Crash When Clearing Array
[ad_1]
On iOS 15, utilizing SwiftUI, if I set a @Revealed 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 about, i.e. the array gadgets are eliminated. The identical happens if I simply set self.object.merchandise = []
shall we say I’ve the next setup:
class ExampleClass: ObservableObject {
static let shared: ExampleClass = ExampleClass()
@Revealed var exampleItem: CustomStructure = CustomStructure(param_1: "", param_2: "")
personal init() {
}
func doSomethingFirst(completion: @escaping (End result<Void, Error>)->Void) {
debugPrint("Did one thing")
completion(.success(Void))
}
func clearExampleItem() {
self.doSomethingFirst { _ in
DispatchQueue.important.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() known as, I get the Index Out of Vary crash from SwiftUI. This does not appear to occur on iOS 16.
Any assist a lot appreciated.
[ad_2]