Swift 搜索栏文本更改错误

Swift 搜索栏文本更改错误,swift,uitableview,search,filter,uisearchbar,Swift,Uitableview,Search,Filter,Uisearchbar,我正在尝试为tableView实现一个搜索栏,但收到错误消息…在我的textDidChange方法中,二进制运算符“==”不能应用于“Place”和“String”类型的操作数。tableView是从Firebase数据库placeList数组填充的。不确定错误源来自何处。提前感谢您的帮助 lazy var searchBar:UISearchBar = UISearchBar() var placeList = [Place]() var placesDictionary = [String

我正在尝试为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上调用filter函数时{$0==searchBar.text!},您所说的是过滤placeList,其中Place对象等于searchBar.text。Place对象不是字符串,您无法比较两种不同的类型。我不熟悉您的数据模型或Place类,但可能您的Place类中有某种类型的字符串属性,可以用来比较?例如,Place had一个名为id的String类型的属性,然后可以通过如下比较进行筛选:filteredData=placeList.filter{$0.id==searchBar.text!}-注意添加的$0.id


您只能将一个字符串与一个字符串进行比较

这很有意义…我确实有一个带有字符串值Place的模型Place NSObject,我的firebase数据模型也有一个名为Place的子值。因此我更新了filteredData=placeList.filter{$0.Place==searchBar.text}但仍然不走运…?当我运行应用程序时,它不会崩溃或给我一个错误-但不会返回搜索栏文本更改输入的筛选结果。@user3708224-因此,按照编写代码的方式,它只会筛选位置字符串与searchBar.text完全相等的位置对象。您可以尝试将两个字符串都改为小写避免任何区分大小写的问题。您可以尝试这样做:placeList.filter{$0.place.lowercased==searchBar.text.lowercased}。如果这仍然不起作用,那么我会认为Firebase中没有一个Place对象的Place字符串与您的搜索文本相等。@user3708224-此外,如果您试图筛选只包含搜索文本但不完全等于的Place字符串,您可以对Swift的字符串使用contains函数API-看起来像这样:placeList.filter{$0.place.lowercased.containssearchBar.text.lowercased}