I have parsed a JSON array which gives me [[String:String]]
which I then put into a table view.
I want to use a UISearchBar
to be able to search the data, but am having trouble because I'm not sure how to deal with the [[String:String]]
format.
I have tried creating another variable which holds the array data as [String]
and I can filter it, but I can't display the results correctly. Sorry if this is a bit confusing as i have confused myself the last couple of hours trying to figure it out. Thank you!
import UIKit
import Alamofire
import SwiftyJSON
class StartViewController: UIViewController, UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource {
var names = [
[String: String]
]()
var isSearching = false
var filteredData = [String]()
@IBOutlet weak
var tableView: UITableView!
@IBOutlet weak
var searchBar: UISearchBar!
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell",
for: indexPath)
let name = names[indexPath.row]
let text: String!
// here I get 'Cannot assign value of type '[String : String]' to type 'String?''
if isSearching {
text = filteredData[indexPath.row]
} else {
text = nil
}
cell.textLabel ? .text = name["name"]
cell.textLabel ? .textColor = UIColor.blue
return cell
}
}
Here are two sections
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchBar.text == nil || searchBar.text == "" {
isSearching = false
view.endEditing(true)
tableView.reloadData()
} else {
isSearching = true
// and here I get 'Binary operator '==' cannot be applied to operands of type '[String : String]' and 'String?''
filteredData = names.filter({
$0 == searchBar.text
})
tableView.reloadData()
}
}
Thanks for the help.
edit: // here is my parsing function if that helps at all
func parse(json: JSON) {
for result in json[].arrayValue {
let name = result["name"].stringValue
let obj = ["name": name]
names.append(obj)
}
tableView.reloadData()
}
}
To be able to display both full and filtered data both arrays must be of the same type.
In
cellForRow
use the array depending onisSearching
In
searchBar:searchDidChange
you have to filter by a key for exampleHowever I recommend to use a custom class or struct rather than a dictionary.