程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了使用 .map 和 .filter 过滤现有数组以创建新的过滤数组大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决使用 .map 和 .filter 过滤现有数组以创建新的过滤数组?

开发过程中遇到使用 .map 和 .filter 过滤现有数组以创建新的过滤数组的问题如何解决?下面主要结合日常开发的经验,给出你关于使用 .map 和 .filter 过滤现有数组以创建新的过滤数组的解决方法建议,希望对你解决使用 .map 和 .filter 过滤现有数组以创建新的过滤数组有所启发或帮助;

在我的一个类中虑以下 init() 函数。以下代码效果很好。最终结果是所有课程现在都在课程地图中。

init() {
    courseRepository.$courses.map { courses in courses.map(Courseviewmodel.init)}
    .assign(to: \.courseviewmodels,on: self)
    .store(in: &cancellables)
}

接下来我想创建第二个地图,其中仅包含当前登录用户创建的课程。以下是不起作用。你们能帮我一把吗?

init() {
    // 1
    courseRepository.$courses.map { courses in courses.map(Courseviewmodel.init)}
    .assign(to: \.courseviewmodels,on: self)
    .store(in: &cancellables)
    
    // add another repository just for the current user's courses
    justMyCourseRepository.$courses.map  =  courseRepository.$courses.map.filter { "\($0.createdby)" == self.authState.loggedInUser!.uID }
    .assign(to: \.justMyCourseviewmodels,on: self)
}

解决方法

您需要将 @H_773_3@map 和 filter 用作单独的函数。您不能只为 justMyCourseRepository.$courses.map 分配一些值。

您可以做的是在应用 filter 之前对元素进行 .map(CourseViewModel.init) - 这样您的原始映射就不会受到影响。

更好的解决方案(由 Leo Dabus 建议)是使用 compactMap一次性完成所有操作:

justMyCourseRepository.$courses
    .map { courses in
        courses
            .compactMap {
                guard "\($0.createdby)" == self.authState.loggedInUser!.uid else {
                    return nil
                }
                return CourseViewModel($0)
            }
    }
    .assign(to: \.justMyCourseViewModels,on: self)
    .store(in: &cancellables)

大佬总结

以上是大佬教程为你收集整理的使用 .map 和 .filter 过滤现有数组以创建新的过滤数组全部内容,希望文章能够帮你解决使用 .map 和 .filter 过滤现有数组以创建新的过滤数组所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:.map使用