首页 > 解决方案 > 在加载单元格之前过滤内容

问题描述

我得到了在加载单元格之前需要过滤的数据模型。具有以下结构:

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
}

标签: swiftfilterprotocols

解决方案


基本上,你要找的是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
}

推荐阅读