swift - 在加载单元格之前过滤内容
问题描述
我得到了在加载单元格之前需要过滤的数据模型。具有以下结构:
struct Food: Decodable {
let title: String?
let content: [Category]?
}
struct Category: Decodable {
let title: String?
let items: [FoodItem]?
}
struct FoodItem: Decodable {
let title: String?
let image: URL?
let summary: String?
}
我将它们加载到UICollectionView
. 我只想要具有title
, image
&的内容summary
。我可以用项目过滤类别。如何在整个Food
数据模型中传播。我可以在技术上for
循环这个。我想知道我可以为每个模型添加一个通用协议/功能来实现相同的效果。
过滤项目
var filteredItem: Bool {
return title != nil && summary != nil && image != nil
}
解决方案
基本上,你要找的是filter(_:)
方法,你可以这样使用:
我认为你有一个数组Food
,所以你想过滤它,因为每个食物的content
( [Category]
) 必须包含items
( [FoodItem]
) 具有非零属性:
// arr: [Food]
let filteredFood = arr.filter { food -> Bool in
var bool = false
food.content?.forEach { $0.items?.forEach({ foodItem in
bool = foodItem.title != nil && foodItem.summary != nil && foodItem.image != nil
})}
return bool
}
推荐阅读
- javascript - 为什么选中复选框时 DOM 没有更新?
- arrays - Fortran:指针数组
- salesforce - 单击按钮后弹出屏幕
- uwamp - .\libraries\plugin_interface.lib.php#532 中的警告
- java - java - 没有检查异常的新inetaddress
- javascript - 警报上的文字
- javascript - 如何更改 highchart 股票 GUI 工具中的默认线条颜色?
- graphql - 将 GraphQL 片段与 Apollo Hooks 一起使用时出错
- c# - 使用反射递归地在 C# 中动态转换
- python - Pandas loc 并将更改应用于数据框问题.. 出现错误 ValueError: cannot reindex from a duplicate axis