Fatal error: Index out of range while animating screens

32 Views Asked by At

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).

enter image description here

`

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.

1

There are 1 best solutions below

0
malhal On

ForEach isn't a for loop, it's a View that needs to be supplied with Identifiable data (so it can track changes), e.g.

ForEach(steps) { step in

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 steps and struct Step: Identifiable