I'm trying to compute a standard deviation with a Core Data fetch request
This works:
let numbers = [1, 2, 3, 4, 4, 5, 9, 11]
let statsExpression = NSExpression(forFunction:"stddev:", arguments:[NSExpression(forConstantValue: numbers)])
let statsValue = statsExpression.expressionValue(with: nil, context: nil) as? Double
This also works:
let request = NSFetchRequest<NSFetchRequestResult>(entityName: Result.entityName(), context: context)
request.resultType = .dictionaryResultType
let avgED = NSExpressionDescription()
avgED.name = "average"
avgED.expression = NSExpression(forFunction: "average:", arguments: [NSExpression(forKeyPath: "amount")])
avgED.expressionResultType = .decimalAttributeType
But changing the NSExpressionDescription in the above code with this crashes:
let stdED = NSExpressionDescription()
stdED.name = "stdDev"
stdED.expression = NSExpression(forFunction: "stddev:", arguments: [NSExpression(forKeyPath: "amount")])
stdED.expressionResultType = .decimalAttributeType
Here is the error I get:
Invalid keypath (request for aggregate operation on a toOne-only keypath): amount