我正在制作一个应用,希望在其中多次过滤锻炼数据。
我曾经在UIKit中借助filter,map,for循环来做到这一点,但是在SwiftUI中却没有运气。
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)
}
}
}
答案 0 :(得分:2)
您必须在可以执行任意代码的地方(例如,在传递给ForEach
的值中)进行过滤-而不是在ForEach
的实际正文中,因为那样做就不会了。期望回到Void
。
例如
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)
}
}
}