Maric Vikike
Maric Vikike

Reputation: 247

How can I filter an array in SwiftUI?

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

Upvotes: 5

Views: 2414

Answers (1)

idolize
idolize

Reputation: 6643

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

Upvotes: 2

Related Questions