简体   繁体   中英

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)'

Any help appreciated.

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
        }

There is no need to loop through results to get the index. You can try this.

var results = context.fetch(request)
if let index = results.index(where: { (result) -> Bool in 
                                        result.value(forKey: "source") == title
                                     })
  {
        results.remove(at: index)
  }

A likely cause of Cannot invoke index with an argument list of type '(of: X)

is because the type X does not conform to Equatable

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

For an array of [X] , use arr.index(where:)


在此处输入图片说明

Update your code as:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM