代码之家  ›  专栏  ›  技术社区  ›  DesperateLearner

加载单元格前过滤内容

  •  0
  • DesperateLearner  · 技术社区  · 5 年前

    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
    }
    
    1 回复  |  直到 5 年前
        1
  •  0
  •   Ahmad F    5 年前

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