我正在尝试为tableView实现一个搜索栏,我收到错误“...二进制运算符'=='不能应用于我的textDidChange方法中'Place'和'String'类型的操作数 . tableView是从Firebase数据库“placeList”数组填充的 . 不确定错误源的来源 . 在此先感谢您的帮助!
lazy var searchBar:UISearchBar = UISearchBar()
var placeList = [Place]()
var placesDictionary = [String: Place]()
var isSearching = false
var filteredData = [Place]()
override func viewDidLoad() {
super.viewDidLoad()
searchBar.searchBarStyle = UISearchBarStyle.prominent
searchBar.placeholder = " Search Places..."
searchBar.sizeToFit()
searchBar.isTranslucent = false
searchBar.backgroundImage = UIImage()
searchBar.delegate = self
searchBar.returnKeyType = UIReturnKeyType.done
navigationItem.titleView = searchBar
tableView.allowsMultipleSelectionDuringEditing = true
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellId)
if isSearching {
cell.textLabel?.text = filteredData[indexPath.row].place
} else {
cell.textLabel?.text = placeList[indexPath.row].place
}
return cell
}
func searchBar(_ searchBar:UISearchBar,textDidChange searchText:String){
if searchBar.text == nil || searchBar.text == "" {
isSearching = false
view.endEditing(true)
tableView.reloadData()
} else {
isSearching = true
// error in below line of code...
filteredData = placeList.filter({$0.place == searchBar.text})
tableView.reloadData()
}
}
1 回答
您的属性
placeList
是Place
对象的数组 . 当您调用数组上的filter
函数(placeList.filter({$0 == searchBar.text!})
)时,您所说的是"filter placeList where a Place object is equal to searchBar.text" . 一个位置对象不是String
,你无法比较两种不同的类型 . 我不熟悉你的数据模型,或者你的Place
类,但是你可以在Place
类中使用某种类型的String属性来比较它?例如,假设Place
有一个名为id
的属性为String的属性,则可以通过比较过滤,如下所示:filteredData = placeList.filter({$0.id == searchBar.text!})
- 注意添加的$0.id
.您只能将String与String进行比较