无法使用类型为((of:Any)'的参数列表调用索引

编程入门 行业动态 更新时间:2024-10-28 09:23:48
本文介绍了无法使用类型为((of:Any)'的参数列表调用索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在制作一个新闻应用程序,您可以在其中选择要查看的主题.我遇到的问题是您取消选择主题.所有选择的主题均在source属性下的一个名为ArticleSource的实体中添加到CoreData中.当我尝试使用字符串title在名为Results的数组中定位主题时,会发生错误.因为我不知道主题在数组中的位置,所以我尝试使用index(of: )方法找到它并产生错误:Cannot invoke index with an argument list of type '(of: Any)'

I am making a news app where you can select topics that you want to see. The problem I am having is where you deselect the topic. All of the selected topics are added to CoreData in an Entity called ArticleSource under the Attribute of source. The error occurs when I try to locate the topic in the array called Results using the string title. As I dont know the position of the topic in the array I try to locate it using index(of: ) method which produces the error: Cannot invoke index with an argument list of type '(of: Any)'

任何帮助表示赞赏.

do { let appDelegate = UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext let request = NSFetchRequest<NSFetchRequestResult>(entityName: "ArticleSource") request.returnsObjectsAsFaults = false var results = try context.fetch(request) if results.count > 0 { for result in results as! [NSManagedObject] { if let source = result.value(forKey: "source") as? String { if source == title { print("it matches") if let index = results.index(of: title) { results.remove(at: index) } } print("results = \(results)") } } } } catch { print("error") } do { let appDelegate = UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext try context.save() print("SAVED") } catch { // error }

推荐答案

在arr.index(of: <Element>)中,元素应符合Equatable,类型X不符合Equatable:

In arr.index(of: <Element>), Element should conform to Equatable, and type X does not conform to Equatable:

对于[X]的数组,请使用arr.index(where:)

将代码更新为:

if let index = results.index(where: { $0 as? String == title }) { print(index) }

更多推荐

无法使用类型为((of:Any)'的参数列表调用索引

本文发布于:2023-11-26 16:34:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634392.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:索引   参数   类型   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!