0

It looks like the standard deviation method for Core Data on iOS does not exists, so I'm trying to do it by hand.

I'm just starting with NSExpression so I'm struggling with this:

let numbers = [4, -2]
let numbersExpr = NSExpression(forConstantValue: numbers)

let avgExpr = NSExpression(forFunction: "average:", arguments: [numbersExpr])
let subExpr = NSExpression(forFunction: "from:subtract:", arguments: [numbersExpr, avgExpr])

let v = subExpr.expressionValue(with: nil, context: nil)

In my subExpr I'm trying to subtract the average to all the values of my numbers array, but it crashes when trying to evaluate v on the last line.

How to do that with NSExpressions?

lorenzo
  • 1,487
  • 1
  • 17
  • 25

1 Answers1

0

It's subExpr that crashes:

let subExpr = NSExpression(forFunction: "from:subtract:", arguments: [numbersExpr, avgExpr])

The built-in from:subtract: expects its arguments to be "two NSExpression objects representing numbers", but your first argument is an array.

NSExpression's built-in functions aren't really designed for vector math. It might be possible to get what you're aiming for with init(block:arguments:). However you wouldn't be able to use that with Core Data (not mentioned in your question, but you used the tag).

Tom Harrington
  • 69,312
  • 10
  • 146
  • 170