3

I am having trouble determining the syntax for reducing an array of a custom managed object subclass in Swift. I have a managed object subclass with a property called amount which is a NSNumber. How do I use the reduce function to get the sum of amount for each item in the array of managed objects. Here is what I have tried, but I get an error stating "could not find member 'amount'".

let reduceSum=myArray.reduce(0) {$0 + $1.amount}

I have looked at this example, but it didn't help since I'm getting the could not find member error.

1 Answer 1

9

Right after posting this, I tried one more thing and it worked. The error message was misleading and made me think the syntax was wrong but the real issue was I needed to convert the NSNumber to a CGFloat. Here is what worked:

let reduceSum=myArray.reduce(0) {$0 + CGFloat($1.amount)}
Sign up to request clarification or add additional context in comments.

3 Comments

Why does the that line not need $0.amount?
If you look at the example I cited in my question, that explains it better than I can. From that link "In the reduce code, the first closure argument ($0) is the running total, which starts at zero, and the second parameter ($1) references a Person object in the people array."
But why do we need to cast it to a CGFloat? It works but why?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.