I am trying to create a search filter using a tableview with multiple sections and get the error 'Cannot assign value of type '[String]' to type 'String' on the line "cell?.textLabel?.text = self.searchArray[indexPath.row].rowTitles". How do I fix this? The ultimate goal is to be able to display the rowTitles in sections of the tableview. Here is my code.
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var tableView: UITableView!
let dataArray = [(sectionTitle: "section 1", rowTitles: ["row 1", "row 2"]),
(sectionTitle: "section 2", rowTitles: ["row 1", "row 2", "row 3"]),
(sectionTitle: "section 3", rowTitles: ["row 1"]),
]
var searchArray = [(sectionTitle: String, rowTitles: [String])]()
var searching = false
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searching {
return searchArray.count
} else {
return dataArray.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "searchCell")
if searching {
cell?.textLabel?.text = self.searchArray[indexPath.row].rowTitles
} else {
cell?.textLabel?.text = self.dataArray[indexPath.row].rowTitles
}
return cell!
}
func numberOfSections(in tableView: UITableView) -> Int {
return self.dataArray.count
}
}
extension ViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
searchArray = dataArray.filter({$0.sectionTitle.lowercased().contains(searchBar.text!.lowercased())} )
searching = true
tableView.reloadData()
}
}