Ios 使用reduce从对象数组填充[String:[CGFloat]]字典
我有一个对象数组,每个对象都有一个类别和一个数量,如下所示: 记录(“账单”,150.00),记录(“杂货”,59.90),等等 我想使用reduce来填充[String:[CGFloat]]字典 应该是这样的: [“账单”:[150.00,140.00,200.00],“杂货”:[59.90,40.00,60.00]] 然而,我不知道如何优雅地实现这一点 我试过(没有成功): 上面返回错误:“不能订阅类型不正确或不明确的值。” 我得到的最接近的结果是:Ios 使用reduce从对象数组填充[String:[CGFloat]]字典,ios,swift,xcode,dictionary,reduce,Ios,Swift,Xcode,Dictionary,Reduce,我有一个对象数组,每个对象都有一个类别和一个数量,如下所示: 记录(“账单”,150.00),记录(“杂货”,59.90),等等 我想使用reduce来填充[String:[CGFloat]]字典 应该是这样的: [“账单”:[150.00,140.00,200.00],“杂货”:[59.90,40.00,60.00]] 然而,我不知道如何优雅地实现这一点 我试过(没有成功): 上面返回错误:“不能订阅类型不正确或不明确的值。” 我得到的最接近的结果是: var dictionary = [St
var dictionary = [String:[CGFloat]]()
dictionary = expenses_week.reduce(into: [:]) { (result, record) in
result[record.category ?? "", default: 0] = [(CGFloat(record.amount))]
这是可行的,但它显然不能满足我的要求
非常感谢您的帮助。您的代码几乎正确。
字典
的值类型是[CGFloat]
,因此下标操作中的默认值必须是空数组,而不是数字0
:
struct Record {
let category: String
let amount: NSNumber
}
let records = [
Record(category: "Bills", amount: 150.00),
Record(category: "Bills", amount: 140.00),
Record(category: "Bills", amount: 200.00),
Record(category: "Groceries", amount: 59.90),
Record(category: "Groceries", amount: 40.00),
Record(category: "Groceries", amount: 60.00),
]
let dictionary = records.reduce(into: [String:[NSNumber]](), {
$0[$1.category] = $0[$1.category] ?? []
$0[$1.category]?.append($1.amount)
})
print(dictionary)
let dictionary = expenses_week.reduce(into: [:]) { (result, record) in
result[record.category ?? "", default: []].append(CGFloat(record.amount))
}
您也可以考虑将CAST移除为<代码> CGFloat < /代码>,然后结果具有类型<代码> [字符串:[双] ] /代码> ./P> 顺便说一句,替代方法(但不一定更有效)将是
let dictionary = Dictionary(expenses_week.map { ($0.category ?? "", [$0.amount]) },
uniquingKeysWith: +)
或
明亮的谢谢你,卡拉姆!
let dictionary = Dictionary(expenses_week.map { ($0.category ?? "", [$0.amount]) },
uniquingKeysWith: +)
let dictionary = Dictionary(grouping: expenses_week, by: { $0.category ?? "" })
.mapValues { $0.map { $0.amount } }