I have two core data entities, proposal and wageClass, and each has a to-many relationship to the other. WageClass has an Int
attribute, numberOfWorkers. I need to sum the array of numberOfWorkers related to each proposal.
Currently I use this:
let proposalNumberOfWorkers = proposal.value(forKeyPath: "wageClasses.numberOfWorkers")
and when I do this:
let arraySum = proposalNumberOfWorkers.reduce(0, +)
I get an error that says type Any has no member reduce. When I eliminate the previous line of code and just try to print the array like this:
totalWorkersLabel.text = "\(proposalNumberOfWorkers!)"
the UILabel
looks like this: {(15)}
(15 being either the first or most recent item in the array, I'm not sure which)
So I'm wondering, 1) how do I make it .reduce, and 2) what the brackets and parens are about. Thanks in advance for your comments!
The brackets and parentheses indicate that proposalNumberOfWorkers!
is an NSSet
. NSSet
does not recognise the reduce
method. NSSet
and Set
are bridged, so you can get what you need by casting proposalNumberOfWorkers
as a Set
:
let proposalNumberOfWorkers = proposal.value(forKeyPath: "wageClasses.numberOfWorkers") as! Set<Int>
and then use reduce
.