gpt4 book ai didi

ios - 使用 reduce 填充 [String : [CGFloat]] dictionary from an object array

转载 作者:搜寻专家 更新时间:2023-11-01 06:26:16 26 4
gpt4 key购买 nike

我有一个对象数组,每个对象都有一个类别和一个数量,如下所示:

Record("Bills", 150.00), Record("Groceries", 59.90), 等等...

我想使用 reduce 来填充 [String:[CGFloat]] 字典。

应该是这样的:

[“账单”:[150.00, 140.00, 200.00],“杂货”:[59.90, 40.00, 60.00] ]

但是,我想不出如何优雅地实现这一目标。

我试过了(没有成功):

var dictionary = [String:[CGFloat]]()
dictionary = expenses_week.reduce(into: [:]) { (result, record) in
result[record.category ?? "", default: 0].append((CGFloat(record.amount)))

以上返回错误:“无法下标不正确或不明确类型的值。”

我得到的最接近的是:

var dictionary = [String:[CGFloat]]()
dictionary = expenses_week.reduce(into: [:]) { (result, record) in
result[record.category ?? "", default: 0] = [(CGFloat(record.amount))]

这行得通,但显然不能满足我的要求。 :)

非常感谢您的帮助。

最佳答案

您的代码几乎是正确的。 dictionary的值类型是[CGFloat],因此下标操作中的默认值必须是空数组,而不是数字0:

let dictionary = expenses_week.reduce(into: [:]) { (result, record) in
result[record.category ?? "", default: []].append(CGFloat(record.amount))
}

您还可以考虑删除对 CGFloat 的转换,然后结果的类型为 [String : [Double]]

顺便说一句,替代(但不一定更有效)的方法是

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 } }

关于ios - 使用 reduce 填充 [String : [CGFloat]] dictionary from an object array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54158906/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com