Cannot invoke index with an argument list of type

2019-03-05 07:13发布

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
        }

3条回答
我想做一个坏孩纸
2楼-- · 2019-03-05 07:27

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

查看更多
可以哭但决不认输i
3楼-- · 2019-03-05 07:38

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


enter image description here

Update your code as:

if let index = results.index(where: { $0 as? String == title }) {
   print(index)
}
查看更多
混吃等死
4楼-- · 2019-03-05 07:46

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)
  }
查看更多
登录 后发表回答