I am running into an error: Fatal error: Index out of range
I would like to know what is out of range since I have 6 values printed in the console and 6 in my JSON that I created. This is happening when I am navigating to the last item. (I already tried similar questions/answers from StackoverFlow with no success).
`
import SwiftUI
public struct Stepper: View {
public enum Step: Equatable {
case fixed, animated(duration: Int)
}
@Binding var selected: Int
let steps: [Step]
@State var timer: Timer?
public init(selected: Binding<Int>, steps: [Step]) {
self._selected = selected
self.steps = steps
}
public var body: some View {
HStack {
ForEach(steps.indices) { item in
StepView(step: steps[item], index: item, selected: $selected)
}
}
.padding(.horizontal,16)
.padding(.vertical,12)
.onChange(of: selected,perform: updateTimer)
.onAppear{
updateTimer(newValue: 0)
}
}
func updateTimer(newValue: Int) {
timer?.invalidate()
guard case .animated(let duration) = steps[newValue] else {
return
} **// the app is crashing here in the guard let **
timer = Timer.scheduledTimer(withTimeInterval: Double(duration),
repeats: false,
block: { _ in
if steps.count > selected + 1 {
withAnimation {
selected += 1
}
}
})
}
}
`
I already tried to update the timer with different values (newValue: ) and to pass item instead of newValue with no success.
ForEachisn't a for loop, it's a View that needs to be supplied withIdentifiabledata (so it can track changes), e.g.How often and in what order the closure is called depends on what kind of subviews are used in it.
You also need
@State var stepsandstruct Step: Identifiable