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
}
A likely cause of
Cannot invoke index with an argument list of type '(of: X)
is because the type
X
does not conform toEquatable
Update your code as:
There is no need to loop through results to get the index. You can try this.