5

I am making an application in which I want to filter an array of workout data more times.

I used to do it by the help of filter, map, for loop in UIKit, but in SwiftUI no luck.

List {
    if workoutsModel.workoutsAreFiltered {
        ForEach(workoutsModel.workoutsFilter) { workoutFilter in
            if workoutFilter.isOn {
                ForEach(self.workoutsModel.workout) { workout in
                    if workoutFilter.name == workout.goal || workout.muscles.contains(workoutFilter.name) {
                        WorkoutsRow(workout: workout)
                    }
                }
            }
        }
    } else {
        ForEach(self.workoutsModel.workout) { workout in
            WorkoutsRow(workout: workout)
        }
    }
}
2
  • 5
    You should do the filtering in the model, not in the UI. Commented Jul 7, 2019 at 21:25
  • How about helping others out? A good answer deserves something, right? Commented Jul 8, 2019 at 1:41

1 Answer 1

2

You have to do the filtering in a place where you can execute arbitrary code (e.g. in the value passed to ForEach) -- not inside the actual body of the ForEach, as that doesn't expect to get back Void.

E.g.

List {
    if workoutsModel.workoutsAreFiltered {
        ForEach(workoutsModel.workoutsFilter) { workoutFilter in
            // Not sure if the `if workoutFilter.isOn` is allowed, so I've instead used it to only iterate an empty array
            ForEach(!workoutFilter.isOn ? [] : self.workoutsModel.workout.filter { workout in
                workoutFilter.name == workout.goal ||
                workout.muscles.contains(workoutFilter.name)
            }) { workout in
                WorkoutsRow(workout: workout)
            }
        }
    } else {
        ForEach(self.workoutsModel.workout) { workout in
            WorkoutsRow(workout: workout)
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Done. Sorry I posted too soon with just the code before I added explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.