搜索栏Swift 3 - 无法在集合中使用/包含运算符

时间:2016-12-23 21:24:08

标签: swift uisearchbar nspredicate

我正在我的项目中实现一个搜索栏,但我收到了以下错误。

  

原因:'不能使用in / contains运算符与集合wellpleased.attendees.UserData(名字:“Ben”,姓:“Delonge”,全名:“Ben Delonge”,公司:“AllStar.com”,jobtitle :“业务发展经理”,图片:“6.jpg”)(不是收藏)'

我已经在NSPredicate周围进行了大量搜索,但似乎无法阻止这种崩溃。

我正在使用下面的代码,任何解决此问题的帮助都将非常感激。

class attendees: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate {

    var tableData = ""

    var value:String!

    var searchString: String = ""

    var dataSource: [UserData] = []
    struct UserData {
        var firstname: String
        var lastname: String
        var fullname: String
        var company: String
        var jobtitle: String
        var image: String
    }




    var filteredAppleProducts = [String]()
    var resultSearchController = UISearchController()

    @IBOutlet weak var tableView: UITableView!

    @IBOutlet weak var searchBar: UISearchBar!

    override func viewDidLoad() {

        print(value)



        searchBar.delegate = self



        self.tableView.reloadData()

        let nib = UINib(nibName: "vwTblCell2", bundle: nil)
        tableView.register(nib, forCellReuseIdentifier: "cell2")


    }

    override func viewDidAppear(_ animated: Bool) {
        getTableData()

    }


    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {


        if filteredAppleProducts != []{

            return self.filteredAppleProducts.count
        }
        else
        {

            if searchString != "[]" {
            return self.dataSource.count
            }else {
                return 0
            }
        }

    }


    // 3
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell  {
        let cell2: TblCell2 = self.tableView.dequeueReusableCell(withIdentifier: "cell2") as! TblCell2

        print(filteredAppleProducts)


         if filteredAppleProducts != []{

            cell2.nameLabel.text = self.filteredAppleProducts[indexPath.row]

            return cell2
        }
        else
        {
            if searchString != "[]"{

                cell2.nameLabel.text = self.dataSource[indexPath.row].fullname
                cell2.companyLabel.text = self.dataSource[indexPath.row].company
                cell2.jobTitleLabel.text = self.dataSource[indexPath.row].jobtitle


                let url = URL(string: "https://www.asmserver.co.uk/wellpleased/backend/profileimages/\(self.dataSource[indexPath.row].image)")
                let data = try? Data(contentsOf: url!) //make sure your image in this url does exist, otherwise unwrap in a if let check / try-catch
                cell2.userImage.image = UIImage(data: data!)

            }
            return cell2


        }
    }

    // 4
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    }

    // 5
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 90
    }


    func updateSearchResults(){


        self.filteredAppleProducts.removeAll(keepingCapacity: false)

        let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchString)
        let array = (self.dataSource as NSArray).filtered(using: searchPredicate)
        self.filteredAppleProducts = array as! [String]

        self.tableView.reloadData()

        print(filteredAppleProducts)


    }


    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        print("searchText \(searchText)")
        print(filteredAppleProducts)

        searchString = searchText
         updateSearchResults()
           }

    func getTableData(){

        self.dataSource.removeAll()



        let defaults = UserDefaults()
        let userid = defaults.string(forKey: "id")

        let url = NSURL(string: "https://www.******.co.uk/wellpleased/backend/searchattendees.php?userid=\(userid!)&eventid=\(value!)")

        print(url)

        let task = URLSession.shared.dataTask(with: url as! URL) { (data, response, error) -> Void in

            if let urlContent = data {

                do {

                    if let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: []) as? [[String:AnyObject]] {


                        var i = 0

                        while i < jsonResult.count {


                            self.dataSource.append(UserData(firstname:"\(jsonResult[i]["firstname"]! as! String)", lastname: "\(jsonResult[i]["lastname"]! as! String)", fullname:"\(jsonResult[i]["fullname"]! as! String)", company: "\(jsonResult[i]["company"]! as! String)", jobtitle:"\(jsonResult[i]["jobtitle"]! as! String)", image:"\(jsonResult[i]["image"]! as! String)"))







                            i = i + 1

                        }

                    }

                } catch {

                    print("JSON serialization failed")

                }

            } else {

                print("ERROR FOUND HERE")
            }

            DispatchQueue.main.async(execute: { () -> Void in


                self.tableView.reloadData()

            })

            self.tableView.isUserInteractionEnabled = true
        }

        task.resume()


    }
}

我也累了:

let searchPredicate = NSPredicate(format: "fullname CONTAINS[c] %@", searchString as String)

返回错误:

  

此类不是密钥全名

的密钥值编码兼容

2 个答案:

答案 0 :(得分:1)

NSPredicate是一个生活在Objective-C世界中的Cocoa功能。它永远不会在UserData数组上工作,因为UserData是一个Swift结构 - 而Objective-C根本看不到Swift结构(即使它可以,它当然也看不到类中的任何类型命名空间,因为你的UserData是)。

如果您只是使用内置的Swift filter方法来过滤dataSource数组,那么您可以轻松完成此操作。例如(如果这是你想要做的):

let array = self.dataSource.filter{$0.fullname.contains(searchString)}

答案 1 :(得分:0)

在Swift 3中,您可以将NSArray与NSPredicate结合使用,如下所示:

let searchPredicate = NSPredicate(format: "%K CONTAINS[c] %@", "fullname",searchString)
let array = NSArray(array: self.dataSource).filtered(using: searchPredicate)