我有一个来自Firebase数据库的产品结构,如下所示:
struct Product {
var name: String
var type: String
var ingredients: String
var price: Double
}
并且我想用部分(产品类型)和相对行填充表格视图。所以我创建了一个具有所有产品类型的数组:
let array = product.compactMap{$0.type}
然后我删除了重复项,并使用了numberofSection和titleForHeaderInSections的最终数组,它可以正常工作。但是现在我只想在每个部分中显示具有相同类型的部分名称的产品。我该如何处理?
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return product.count
}
filter
:func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return product.filter { $0.type == "myType" }.count
}
let dict = Dictionary(grouping: product, by: { $0.type})
然后使用您的类型数组访问它
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let type = typesArray[section] guard let count = dict[type]?.count else { return 0 } return count }
另一个选择是直接使用数组索引作为键来创建字典,以便可以直接在tableView:numberOfRowsInSection中使用
Dictionary(grouping: product, by: { typesArray.firstIndex(of: prod.type)! })