I am working for search filter based on user input. I have these following object model
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]()
}
So I have a tableView that will populate the filter result.
var dataSource = [ProductDO]()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if self.dataSource.count > 0 {
return self.dataSource.count
}
return 1
}
For my thinking it is best to collect the result as ProductDO and then populate data, because sometimes this might happen, User types "C":
Curry Rice -> Category: Food
Coke -> Category: Beverages
So what I have now is this code. I retrieve all the menu item that is saved inside the database and then filter it.
// This will result an array that is type of: MenuItemDO
let menuItemCategoryfilteredArray = menuItemArray.filter({$0.categoryName?.lowercased() == searchBar.text?.lowercased()})
Basically the user will be able to search by the category name or the product name directly.
My problem is, how can I filter the user input and then cast it to ProductDO?
Usually I will just filter based on the "Parent" of the model object, in this case MenuItemDO, but it seems in this scenario, I couldn't do it because it will be irrelevant to the tableView dataSource
Can anyone guide me please? Thanks
Something like this?:
let products = menuItemArray.filter {
$0.categoryName?.range(of: "search text", options: .caseInsensitive) != nil
}.flatMap { $0.products }
Unlike map(_:)
method, flatMap(_:)
will flatten the $0.products
array into a single array.
what you have to do is apply map
on your filtered array.
let finalArray = menuItemCategoryfilteredArray.map{$0.products}
This will return [[ProductDO]]
. Hope this will help :).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.