我正在根据用户输入进行搜索过滤器。我有以下这些对象模型
public class MenuItemDO: DomainEntity {
public var categoryId: String?
public var categoryName: String?
public var products = [ProductDO]()
}
public class ProductDO: Mappable {
public var itemName: String?
public var price: Double = 0.0
public var dynamicModifiers = [DynamicModifierDO]()
}
所以我有一个表视图,它将填充过滤结果。
var dataSource = [ProductDO]()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if self.dataSource.count > 0 {
return self.dataSource.count
}
return 1
}
在我看来,最好将结果收集为 ProductDO,然后填充数据,因为有时可能会发生这种情况,用户类型"C":
Curry Rice -> Category: Food
Coke -> Category: Beverages
所以我现在拥有的是这段代码。我检索保存在数据库中的所有菜单项,然后对其进行过滤。
// This will result an array that is type of: MenuItemDO
let menuItemCategoryfilteredArray = menuItemArray.filter({$0.categoryName?.lowercased() == searchBar.text?.lowercased()})
基本上,用户将能够直接按类别名称或产品名称进行搜索。
我的问题是,如何过滤用户输入,然后将其转换为 ProductDO?
通常我只会根据模型对象的"父"进行过滤,在本例中为 MenuItemDO,但似乎在这种情况下,我无法这样做,因为它与 tableView 数据源无关
谁能指导我?谢谢
像这样吗?
let products = menuItemArray.filter {
$0.categoryName?.range(of: "search text", options: .caseInsensitive) != nil
}.flatMap { $0.products }
与map(_:)
方法不同,flatMap(_:)
会将$0.products
数组展平为单个数组。
你要做的是在过滤后的数组上应用map
。
let finalArray = menuItemCategoryfilteredArray.map{$0.products}
这将返回[[ProductDO]]
。希望这对:)有所帮助。