So my goal is to make a search bar for my tableView. My data is a 2D array of objects, "GiftData". It's a very simple object, it's only two properties are "gift:" and "picture:" and I only want to search by "gift:" which is just a string. The reason it is a 2D array is because I am using a separate array of sections to divide the tableView. Onto the problem, I cannot for the life of me get this filtering code to compile, please help. GIFT DATA Object:
class GiftData {
var gift = ""
var picture: UIImage
init (gift: String, picture: UIImage) {
self.gift = gift
self.picture = picture
}
func match (search: String) -> Bool {
return (gift.caseInsensitiveCompare(search) == ComparisonResult.orderedSame)
}
static func createData () -> [[GiftData]] {
return [[GiftData(gift: "necklace", picture: UIImage(named: "heart-emoji-png-2")!)], [GiftData(gift: "tie", picture: UIImage(named: "Hugging_Face_Emoji_2028ce8b-c213-4d45-94aa-21e1a0842b4d_large")!)], [GiftData(gift: "cane", picture: UIImage(named: "ios_emoji_kissing_face_with_closed_eyes")!)], [GiftData(gift: "shoes", picture: UIImage(named: "Nerd_with_Glasses_Emoji")!)]]
}
Filtering code:
extension SecondViewController: UISearchResultsUpdating, UISearchDisplayDelegate {
func updateSearchResults(for searchController: UISearchController) {
filterForSearch(searchText: searchController.searchBar.text!)
}
func filterForSearch (searchText: String) {
giftResults = giftData.filter{(dataArray: [GiftData]) -> Bool in
return dataArray.filter({(gift) -> Bool in
return gift.match(search: searchText)})
}
giftTableView.reloadData()
}
It says "Cannot invoke filter with an argument list of type '((GiftData) throws Bool)'. After toying around for hours, I just can't seem to understand what I'm dealing with here.
The problem is here:
func filterForSearch (searchText: String) {
giftResults = giftData.filter{(dataArray: [GiftData]) -> Bool in
return dataArray.filter({(gift) -> Bool in
return gift.match(search: searchText)})
}
giftTableView.reloadData()
}
So, you are filtering arrays of string. You should return Bool value in first filter{
closure, but you return GiftData which is a result of second(internal) filter{
closure🙃
If giftResults is [[GiftData]] :
func filterForSearch (searchText: String) {
giftResults = giftData.map{
return $0.filter({(gift) -> Bool in
return gift.match(search: searchText)})
}
giftTableView.reloadData()
}
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.