Reputation: 2792
I'm filtering in a 2D array where I only want to get the result if there are any values in each section.
struct SectionObject: Comparable {
var sectionName: String
var sectionObjects: [SectionValues]
static func < (lhs: TagObjects, rhs: TagObjects) -> Bool {
return lhs.sectionName < rhs.sectionName
}
static func == (lhs: TagObjects, rhs: TagObjects) -> Bool {
return lhs.sectionName == rhs.sectionName
}
}
In my extension of searchBarDelegate I'm filtering the objects by:
//var filterArray: [SectionObject]
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchText.isEmpty {
filterArray = sectionsArray
return
}
filterArray = sectionsArray.map({
let existingValues = $0.sectionObjects.filter({ $0.value.contains(searchText) })
// if existingValues.count == 0 { continue }
return SectionObject.init(sectionName: $0.sectionName, sectionObjects: existingValues)
})
}
It's working as I want it, but sometimes the result can be 0 (and not nil), so I can't be using the compactMap
to skip the section.
I can solve this by just filtering again where sectionObjects.count != 0
, but I wonder if it's possible in any way to just include the continue
in the array mapping?
Upvotes: 0
Views: 45
Reputation: 273143
You can use compactMap
! Just return nil
instead of continue
:
filterArray = sectionsArray.compactMap({
let existingValues = $0.sectionObjects.filter({ $0.value.contains(searchText) })
if existingValues.isEmpty { return nil }
return SectionObject.init(sectionName: $0.sectionName, sectionObjects: existingValues)
})
This works because compactMap
will remove those elements that are mapped to nil
.
Upvotes: 1