Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3 Core Data - NSExpression forFunction: "sum:" throws error ("could not cast dictionary to Day")

I have days and tasks. A day has many tasks. Every task has an attribute called "points" and I want to sum all points of the tasks of the current day. I used the code below (found in the book Core Data by tutorials, swift 2 version) and tried to modify it for swift 3 (I also added a predicate, but that's not important). But when I run this code, I get this error:

Could not cast value of type 'NSKnownKeysDictionary1' (0x10d02d328) to 'MyProject.Day'

What am I doing wrong?

    // sum current day's task points 
    let sumRequest: NSFetchRequest<Day> = Day.fetchRequest()
    sumRequest.resultType = .dictionaryResultType

    sumRequest.predicate = NSPredicate(format: "SELF == %@", argumentArray: [Project.Days.current])

    let expressionDescription = NSExpressionDescription()
    expressionDescription.name = "sumOfPoints"
    expressionDescription.expression = NSExpression(forFunction: "sum:", arguments: [NSExpression(forKeyPath: "tasks.points")])
    expressionDescription.expressionResultType = .integer16AttributeType

    sumRequest.propertiesToFetch = [expressionDescription]

    do {
        let results = try managedObject.fetch(sumRequest) as! [NSDictionary] // Here's the line that causes the error
        print("DEN:", results)
    } catch let error as NSError {
        print("DEN:", error.localizedDescription)
    }

I think it has something to do with this line:

let sumRequest: NSFetchRequest<Day> = Day.fetchRequest()

Here, I explicitly say the result will be a Day (I believe that's new in swift 3?). But I don't know how I could change this.

Thank you!

like image 930
Quantm Avatar asked Sep 15 '16 22:09

Quantm


1 Answers

This solves my problem:

let sumRequest: NSFetchRequest<NSFetchRequestResult> = Day.fetchRequest()

Instead of putting Dayas NSFetchRequestResult, I put NSFetchRequestResult itself there. Now it's working.

I believe as I set it to a different resultType it's not [Day]anymore that gets returned, so that's why I needed to change that to be more generic or something.

like image 133
Quantm Avatar answered Oct 07 '22 09:10

Quantm