Reputation: 279
As you can see here in my code, I have nested Array/Dictionary and the search I have to make in different keys together, just like student_name, (student_name) is inside in student Dictionary, everything working perfectly, but the only issue I am facing here is, whatever searchBar found I have to show in cell but due to nested dictionary I am not getting how to show in cell.
cell.nameLbl.text = (What should I write here to show found values???)
if I have to create one more array to append values that searchBar found then question is what should I write in code ( what I am appending? )
var foundName:[String] = [] (Declared global variable to save only string that already matched)
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filteredData = schoolData.filter{(item:School?) -> Bool in
return ((item?.resultMap["teacher"] as? String)?.range(of: searchText, options: .caseInsensitive, range: nil, locale: nil) != nil) ||
((item?.resultMap["class"] as? String)?.range(of: searchText, options: .caseInsensitive, range: nil, locale: nil) != nil) ||
((((item?.resultMap["student"]) as? [String: Any?])?["student_name"] as? String)?.range(of: searchText, options: .caseInsensitive, range: nil, locale: nil) != nil)
}
foundName.append(contentsOf: (what should I write here .. ))
tableView.reloadData()
}
}
Upvotes: 0
Views: 132
Reputation: 279
here is the answer of my question, I figured it out finally.
if let title = item?.resultMap["teacher"] as? String, title.prefix(2) == searchText {
self.foundName.append(item?.resultMap["teacher"] as? String ?? "")
}
For cell thats the code I had wrote,
cell.nameLbl.text = foundName[indexPath.row]
Upvotes: 0
Reputation: 2714
You will have to create an array that holds the search values. This array should be populated in func searchBar.
cell.nameLbl.text = (What should I write here to show found values???)
var foundNames: [String] = []
cell.nameLbl.text = foundNames[indexPath.row]
Modify search func to populate the values found and use map to return only the results (of any of the fields searched) as string array. I've provided an example below of how you can convert the schoolData object to return an array of school names.
func searchBar(_ searchBar: UISearchBar? = nil, textDidChange searchText: String) {
let filteredData = schoolData.filter { item in
return (item.name?.range(of: searchText, options: .caseInsensitive, range: nil, locale: nil) != nil)
}
foundNames = filteredData.map({
($0.name ?? "")
})
}
Here's is the sample data I used.
var schoolData: [School] = [School(id: 1, name: "First"),
School(id: 2, name: "Second"),
School(id: 3, name: "Third"),
School(id: 4, name: "Four")]
class School {
var id: Int?
var name: String?
init(id: Int, name: String) {
self.id = id
self.name = name
}
}
Let me know if you have any questions.
Upvotes: 1