I have a datasource made like this:
[(header: String?, cells: [CustomObject])]
Lets say customObject as a field name
.
Now I need to filter my dataSource by name
given by the searcher text.
How do I filter all elements that contains this given text in my CustomObject name value?
I would have done something like this if I haven't a tuple:
filteredDataSource = dataSource.filter({
return $0.questionTitle.lowercased().contains(searchText.lowercased())
})
UPDATE:
The main datasource is composed like this:
header: Europe cells: CustomObject("Italy), CustomObject("Germany)...
header: Africa cells: CustomObject("Congo")...
By filtering with the searched text (For example Italy), the cells are correctly filtered! But the header is not filtered accordingly. So I receive:
header: Africa cells: CustomObject("italy)
for example...
How do I filter cells with the searchedText and headers accordingly?
CodePudding user response:
You can use compactMap
for this and filter your nested array and return nil if there isn't any match in nested array.
let search = searchText.lowercased()
let filteredArray = tupleArray.compactMap({
let filteredCells = $0.cells.filter({ $0.name.lowercased().contains(search) })
return filteredCells.isEmpty ? nil : ($0.header, filteredCells)
})