大佬教程收集整理的这篇文章主要介绍了使用 .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,请注明来意。