如何在 SwiftUI 中过滤数组? [英] How can I filter an array in SwiftUI?

查看:28
本文介绍了如何在 SwiftUI 中过滤数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个应用程序,我想在其中多次过滤一组锻炼数据.

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

我曾经在 UIKit 中借助 filter、map 和 for 循环来做到这一点,但在 SwiftUI 中却没有.

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

推荐答案

您必须在可以执行任意代码的地方进行过滤(例如在传递给 ForEach 的值中)--不在 ForEach 的实际主体内,因为它不希望返回 Void.

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.

例如

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

这篇关于如何在 SwiftUI 中过滤数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆