Swift 3 Master Data - NSExpression forFunction: "sum:" throws an error ("cannot use dictionary for day")

I have days and tasks. The day has many tasks. Each task has a “point” attribute, and I want to summarize all the points of the tasks of the current day. I used the code below (found in the Core Data book on tutorials, version swift 2) and tried to change it for swift 3 (I also added a predicate, but that doesn't matter). But when I run this code, I get this error:

Unable to pass value like "NSKnownKeysDictionary1" (0x10d02d328) to "MyProject.Day"

What am I doing wrong?

    // sum current day 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 the line that causes the error
        print("DEN:", results)
    } catch let error as NSError {
        print("DEN:", error.localizedDescription)
    }

I think this has something to do with this line:

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

Here I clearly state that the result will be Day (I believe that the new in fast 3?). But I do not know how to change this.

!

+4
1

:

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

, Day NSFetchRequestResult, NSFetchRequestResult. .

, resultType it not [Day], - .

+8

Source: https://habr.com/ru/post/1654751/


All Articles