Index out of range when binding a Slider value to a nested array in EnvironmentObject

醉酒当歌 提交于 2019-12-01 14:20:23

I'm still going through your code. But I'd like to comment on something that caught my eye in your functions addStepX():

    func addStep1() {
        let newStep = Step(id: UUID(), name: "Step #1", parameters: [Parameter]())
        currentStep = newStep
        steps.insert(newStep, at: steps.count)
    }

Are you aware that the steps.insert() will not trigger a didSet, and so the didChange.send() will not execute? I propose you invert the order and first insert the step, and later you update currentStep. This way you call didChange.send() exactly once, after all your changes are done.

    func addStep1() {
        let newStep = Step(id: UUID(), name: "Step #1", parameters: [Parameter]())
        steps.insert(newStep, at: steps.count)
        currentStep = newStep
    }

Note that changing that still does not fix the problem, but I though I should mention, as it is definitely a problem.

UPDATE

After your changes, the code looks much cleaner. And I seem to have found a way of preventing the out of bounds.

It seems the problem is due to a timing issue. Your array gets updated, but the parameter passed by the List is still old. Eventually, it will catch up, but because of the out of bound crash... it never does. So why not make it conditional?

Note that I also added the slider value to the Text() view, to make it evident that the binding is successful:

struct ParameterRow: View {
    @EnvironmentObject var recipe: Recipe
    @State var sliderValue:Float = 30
    var parameter: Parameter!

    init(parameter: Parameter) {
        self.parameter = parameter
    }

    var body: some View {
        VStack {
            Text("\(parameter.name) = \(parameter.id < recipe.currentStep.parameters.count ? recipe.currentStep.parameters[parameter.id].current : -1)")
            Slider(
                value: parameter.id < recipe.currentStep.parameters.count ? $recipe.currentStep.parameters[parameter.id].current : .constant(0),
                from: parameter.minimum,
                through: parameter.maximum,
                by: 1.0
            )
        }
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!