本文介绍了无法使用类型为((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
        }

推荐答案

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


将代码更新为:

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

这篇关于无法使用类型为((of:Any)'的参数列表调用索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 05:00