如何组合字典中的重复键并快速汇总值?

时间:2020-09-02 12:08:48

标签: arrays swift dictionary filter swift3

var dictionary: [String : Any] = [:]
              
for revenueItem in revenues {                        
    if let currentValue = dictionary[revenueItem.customerName] {                    
        dictionary[revenueItem.customerName] = [currentValue] + [revenueItem.revenue]
        print("hellooooooooooo \(currentValue)")
    } else {
        dictionary[revenueItem.customerName] = [revenueItem.revenue]
    }
}

就像我有2个具有相同键但值不同的客户名。我想对它们的值求和,并在输出中只做一个键,但是有一个总值。 在我的表格视图中,单元格显示为重复且未汇总值,并且customername(键)也重复。请帮忙..我尝试了一切,但未能纠正输出。

1 个答案:

答案 0 :(得分:1)

您可以使用Dictionary.init<S>(_ keysAndValues: S, uniquingKeysWith combine: (Value, Value) throws -> Value),它使用Sequence个元组,存储键值对和一个闭包,闭包定义了如何处理重复的键。

// Create the key-value pairs
let keysAndValues = revenues.map { ($0.customerName, $0.revenue) }
// Create the dictionary, by adding the values for matching keys
let revenueDict = Dictionary(keysAndValues, uniquingKeysWith: { $0 + $1})

测试代码:

struct RevenueItem {
    let customerName: String
    let revenue: Int
}

let revenues = [
    RevenueItem(customerName: "a", revenue: 1),
    RevenueItem(customerName: "a", revenue: 9),
    RevenueItem(customerName: "b", revenue: 1)
]

let keysAndValues = revenues.map { ($0.customerName, $0.revenue) }
let revenueDict = Dictionary(keysAndValues, uniquingKeysWith: { $0 + $1})
revenueDict // ["a": 10, "b": 1]