如何合并字典中的重复键并求和 swift 中的值?

how to combine duplicate key in dictionary and sum up values in swift?

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 个客户名称,它们具有相同的键但不同的值。我想总结他们的价值并在输出中只制作一个键但有一个总价值。 在我的 tableview 单元格中出现重复并且不总结值并且客户名(键)也重复。请帮助..我尝试了一切但未能更正输出。

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

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

测试代码:

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 { ([=11=].customerName, [=11=].revenue) }
let revenueDict = Dictionary(keysAndValues, uniquingKeysWith: { [=11=] +  })
revenueDict // ["a": 10, "b": 1]