gpt4 book ai didi

swift - 搜索栏 textDidChange 错误

转载 作者:行者123 更新时间:2023-11-28 15:38:43 25 4
gpt4 key购买 nike

我正在尝试为 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()
}

}

最佳答案

您的属性 placeList 是一个 Place 对象数组。当您在数组 (placeList.filter({$0 == searchBar.text!})) 上调用 filter 函数时,您所说的是“filter placeList where a Place 对象等于 searchBar.text”。地点对象不是 String,您不能比较两种不同的类型。我不熟悉您的数据模型或您的 Place 类,但也许您的 Place 类中有某种类型的 String 属性可以用来比较?例如,假设 Place 有一个名为 id 的字符串类型的属性,然后您可以像这样通过比较进行过滤:filteredData = placeList.filter({$0.id == searchBar.text!}) - 注意添加的 $0.id

你只能比较一个字符串和一个字符串

关于swift - 搜索栏 textDidChange 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43990566/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com