I have an array of objects, which each have a category and an amount, as below:
Record("Bills", 150.00), Record("Groceries", 59.90), etc...
I'd like to use reduce to populate a [String:[CGFloat]] dictionary.
It should be like this:
[ "Bills" : [150.00, 140.00, 200.00] , "Groceries" : [59.90, 40.00, 60.00] ]
However, I can't figure out how to achieve this elegantly.
I've tried (with no success):
var dictionary = [String:[CGFloat]]()
dictionary = expenses_week.reduce(into: [:]) { (result, record) in
result[record.category ?? "", default: 0].append((CGFloat(record.amount)))
The above returns the error: "Cannot subscript a value of incorrect or ambiguous type."
The closest I've gotten is:
var dictionary = [String:[CGFloat]]()
dictionary = expenses_week.reduce(into: [:]) { (result, record) in
result[record.category ?? "", default: 0] = [(CGFloat(record.amount))]
That works, but it doesn't do what I want, obviously. :)
I would greatly appreciate your help.