“不能在集合中使用 in/contains 运算符”

2024-05-22

单击搜索栏时出现此错误:

由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“无法在集合中使用 in/contains 运算符”Assignment_4.SearchResult(studentID:“1060”,lastName:“Squarepants”,firstName:“Spongebob”,专业:“Krusty Krab” Chef”,年份:“Junior”,gpa:“4.0”)(不是集合)'

得到这一行的错误。

let array = (results as NSArray).filtered(using: searchPredicate)

这是整个代码。我不明白出了什么问题。谢谢!!

var results = [SearchResult]()
var indexN = 0
var addStudent = false
var searchController: UISearchController!

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


@IBAction func AddStudentButton(_ sender: Any) {
    addStudent=true
    performSegue(withIdentifier: "detailSegue", sender: self)
}

@IBAction func refreshButton(_ sender: Any) {
    refreshTable()
}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    listTableView.delegate = self
    listTableView.dataSource = self

    listTableView.reloadData()

    jsonParser()

    self.resultSearchController = ({

        let controller = UISearchController(searchResultsController: nil)

        controller.searchResultsUpdater = self

        controller.dimsBackgroundDuringPresentation = true

        controller.searchBar.sizeToFit()



        self.listTableView.tableHeaderView = controller.searchBar



        return controller

    })()
    self.listTableView.reloadData()


}

/*
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
}
*/

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

    if (self.resultSearchController.isActive) {

        return self.filteredTableData.count

    }

    else {

        return self.results.count

    }

    // return self.results.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell:UITableViewCell = UITableViewCell(style:UITableViewCellStyle.subtitle, reuseIdentifier: "cell")
    //cell.textLabel!.text = self.results[indexPath.row].firstName + " " + results[indexPath.row].lastName
    //return cell

   // let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)



    if (self.resultSearchController.isActive) {

        cell.textLabel?.text = filteredTableData[indexPath.row]



        return cell

    }

    else {

        cell.textLabel?.text = self.results[indexPath.row].firstName + " " + results[indexPath.row].lastName
        return cell

    }

}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    indexN = indexPath.row
    addStudent=false
    performSegue(withIdentifier: "detailSegue", sender: self)
}

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if (editingStyle == UITableViewCellEditingStyle.delete) {
        // handle delete (by removing the data from your array and updating the tableview)
        Delete(studentID: self.results[indexN].studentID)
        refreshTable()
    }
}

func numberOfSections(in tableView: UITableView) -> Int {

    return 1

}




override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func jsonParser() {
    let urlPath = "http://csmadison.dhcp.bsu.edu/~vjtanksale/cs320/selectstudents.php"
    guard let endpoint = URL(string: urlPath) else {
        print("Error creating endpoint")
        return
    }
    let request = URLRequest(url: endpoint)
    URLSession.shared.dataTask(with: request) { (data, response, error) in
        do {
            guard let data = data else {
                return
            }
            guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [[String:AnyObject]] else {
                print("No idea")
                return
            }

            for result in json {
                if let student = SearchResult(json: result) {
                    self.results.append(student)
                }
            }
            self.grabData()
        } catch let error as NSError {
            print(error.debugDescription)
        }
        }.resume()
}

func grabData() {
    DispatchQueue.main.async {
        self.listTableView.reloadData()
    }
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if(addStudent==false){
        let newVC: DetailViewController = segue.destination as! DetailViewController
        newVC.result = results[indexN]
        newVC._label1 = results[indexN].studentID
        newVC._label2 = results[indexN].lastName
        newVC._label3 = results[indexN].firstName
        newVC._label4 = results[indexN].major
        newVC._label5 = results[indexN].year
        newVC._label6 = results[indexN].gpa
    }
    else if(addStudent==true){
        let newVC: DetailViewController = segue.destination as! DetailViewController
        newVC.addStudent=true
    }

}

func Delete(studentID: String) {
    let request = NSMutableURLRequest(url: NSURL(string: "http://csmadison.dhcp.bsu.edu/~vjtanksale/cs320/deletestudents.php")! as URL)
    request.httpMethod = "POST"
    let postString = "StudentId="+studentID
    request.httpBody = postString.data(using: String.Encoding.utf8)

    let task = URLSession.shared.dataTask(with: request as URLRequest) {
        data, response, error in

        if error != nil {
            print("error=\(error)")
            return
        }

        print("response = \(response)")

        let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
        print("responseString = \(responseString)")
    }
    task.resume()
}

func refreshTable(){
    results.removeAll()
    self.listTableView.reloadData()
    jsonParser()
    self.listTableView.reloadData()
}

func updateSearchResults(for searchController: UISearchController)

{

    filteredTableData.removeAll(keepingCapacity: false)



    let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text!)

    let array = (results as NSArray).filtered(using: searchPredicate)

    filteredTableData = array as! [String]



    self.listTableView.reloadData()

}

}


您收到此错误是因为您尝试使用CONTAINS谓词于SearchResult对象,它们不是具有定义概念的集合CONTAINS。这个错误发生在运行时,因为NSPredicate在运行时解析并处理其字符串。为此,最好使用本机 swift 设施:

let searchTerm = searchController.searchBar.text!

let array = results.filter { result in
    return result.studentID.contains(searchTerm) ||
           result.something.contains(searchTerm) // and so on...
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

“不能在集合中使用 in/contains 运算符” 的相关文章

随机推荐

  • 在 Android 上提取/修改视频帧

    我有一个视频文件 我想获取视频的每一帧并对帧进行一些修改 例如在其中绘制另一个位图 放置一些文本等 Android 中是否有任何 API 框架可用于从视频中获取帧 我在 iOS 中使用他们的 AVFramework 做了类似的事情 如果可以
  • 如何在没有 DROP 数据库权限的情况下从命令行删除所有 MySQL 表? [复制]

    这个问题在这里已经有答案了 如何使用命令提示符删除 Windows MySQL 中的所有表 我想这样做的原因是我们的用户有权访问数据库删除 但无权重新创建数据库本身 因此我们必须手动删除表 有没有办法一次删除所有表 请记住 大多数表都与外键
  • 开源机器翻译引擎?

    我们正在寻找一个可以合并到我们的本地化工作流程中的开源机器翻译引擎 我们正在考虑以下选项 Moses http www statmt org moses C Joshua http www computing dcu ie mforcada
  • Spring验证非空元素的字符串列表

    我有一个模型类 其中包含字符串列表 该列表可以为空 也可以包含元素 如果它有元素 这些元素不能为空 举个例子 假设我有一个名为 QuestionPaper 的类 它有一个 QuestionId 列表 其中每个都是一个字符串 class Qu
  • Django 多个外键,相同的相关名称

    我想创建一个模型 1 其中具有相同其他模型 2 的多个外键 我希望这些外键具有相同的related name因为每个外键将指向 model 2 的不同实例 因为我需要所有外键的一个反向关系 也许一个例子会更明确 class Parent M
  • iOS-将图像转为视频时,CVPixelBufferCreate内存无法正确释放

    我正在将图像制作成视频 但总是因为内存警告而崩溃 分配太多CVPixelBufferCreate 我不知道如何正确处理 我看过很多类似的主题 但没有一个能解决我的问题 这是我的代码 void writeImagesArray NSArray
  • 在java中加密字符串,在node.js中解密,错误:解密失败

    我正在尝试用 java 加密一个字符串 将其发送到我的 node js 服务器 然后解密 但是 当我尝试执行此操作时 尝试解密时会不断出现错误 Java加密 String privateKey someprivatekey String d
  • WPF KeyGestures - 绑定非字母数字键

    Should be a simple one but I can t work out how to do it Using WPF4 I want to Bind Ctrl to Zoom Out and Ctrl to Zoom In
  • 如何仅更改 DateTime 的日期部分,同时保留时间部分?

    我在代码中使用了很多 DateTime 我想将这些日期时间更改为我的特定日期并保留 时间 1 2012 02 02 06 00 00 gt 2015 12 12 06 00 00 2 2013 02 02 12 00 00 gt 2015
  • 如何配置 nginx 重写规则以使 CakePHP 在 CentOS 上运行?

    大家好 请帮帮我 我正在尝试在运行 Nginx 和 Fact CGI 的 Centos 服务器上设置 cakephp 环境 我已经在服务器上运行了一个 WordPress 站点和一个 phpmyadmin 站点 因此我已经正确配置了 PHP
  • 为什么我们需要`ngDoCheck`

    我似乎不明白为什么我需要ngDoCheck生命周期钩子除了用于简单的通知之外 特别是在其中编写代码如何对更改检测产生影响 我发现的大多数例子都显示了无用的例子 比如this one https juristr com blog 2016 0
  • EclipseLink MOXy:XmlPath 注释中的逻辑运算符

    逻辑运算符在 EclipseLink MOXy 的 XmlPath 注释中工作吗 我尝试过但无法使其工作 没有抛出异常 并且没有任何内容绑定到 元素 例如 我想在绑定文件中包含如下内容
  • 避免函数内装箱/拆箱

    对于数字密集型代码 我编写了一个具有以下签名的函数 def update f Int Int Double gt Double Unit 然而 因为Function3不是专门的 每个应用程序f结果对 3 个参数和结果类型进行装箱 拆箱 我可
  • C++0x 中的新 unicode 字符

    我正在构建一个 API 它允许我获取各种编码的字符串 包括 utf8 utf16 utf32 和 wchar t 根据操作系统 可能是 utf32 或 utf16 新的 C 标准引入了新类型char16 t and char32 t没有这么
  • 将 .p12 证书存储在钥匙串中以供稍后使用

    我正在尝试按照 Apple 文档处理此处的客户端 p12 证书 https developer apple com library ios documentation Security Conceptual CertKeyTrustProg
  • 加载腌制字典对象或加载 JSON 文件哪个更快? [关闭]

    Closed 这个问题不符合堆栈溢出指南 help closed questions 目前不接受答案 什么更快 A Unpickling 加载 一个 pickled 字典对象 使用pickle load or B 使用以下命令将 JSON
  • Windows 上 libcurl 的静态库[重复]

    这个问题在这里已经有答案了 如何将此库 libcurl 静态链接到 exe 我努力了 disable share enable static 没有帮助 我使用的是MingW32 有没有一种简单的方法来静态链接这个库 这样我的应用程序就不再有
  • 使用自定义挂载点使用 docker 卷创建卷

    我需要使用个人挂载点 mountpoint my path 而不是 var lib docker 创建一个带有 dockervolume 的卷 但我不能使用像local persist这样的插件 docker volume create d
  • 如何修复这个 delphi 7 编译错误 - “重复资源”

    我正在尝试编译我继承的 Delphi 7 项目 但收到此错误 错误 警告 重复资源 错误 类型 2 位图 ID 编辑 错误 文件 C 路径缩短 common CRGrid res 资源已保留 文件 c common raptree RES
  • “不能在集合中使用 in/contains 运算符”

    单击搜索栏时出现此错误 由于未捕获的异常 NSInvalidArgumentException 而终止应用程序 原因 无法在集合中使用 in contains 运算符 Assignment 4 SearchResult studentID