Mitu Vinci
Mitu Vinci

Reputation: 465

Filter a two dimensional array in table view for searching in Swift

I have a two dimensional array

fileprivate var Food : [[FoodModel]] = [[]]

Food = [["Apple","Mango"],["Chocolate","Biscuit"]]

and two sections

let section = ["Fruits","Dry Food"]

for a table view. It's displaying the value nicely. Now I added a search bar for searching value from Food. My problem is that I can't filter Food by my searching keyword.

Food.filter({}) //what to write here?
self.tableView.reloadData()

Upvotes: 1

Views: 2986

Answers (2)

RajeshKumar R
RajeshKumar R

Reputation: 15748

Try this

let searchString = "Choco"

var result = Food.filter { (dataArray:[FoodModel]) -> Bool in
    return dataArray.filter({ (FoodModel) -> Bool in
        return FoodModel.containsString(searchString)
    }).count > 0
}

Upvotes: 3

haider_kazal
haider_kazal

Reputation: 3468

You could try the following:

var searchResult = Food.flatMap({ $0 }).filter { $0.lowercased().contains(searchedKeyword) }

Firstly, the flatMap flattens the array of array to single array, then filters to that resulting array.

Upvotes: 4

Related Questions