minios dwarf
minios dwarf

Reputation: 17

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

like i have a 2 customer name with the same keys but different values. i want to sum up their values and make only one key in output but have a total value. In my tableview cell appears duplicated and not sum up the values and the customername (key) is also duplicated. please help.. i tried everything but failed to correct the output.

Upvotes: 1

Views: 1501

Answers (1)

David Pasztor
David Pasztor

Reputation: 54745

You can use Dictionary.init<S>(_ keysAndValues: S, uniquingKeysWith combine: (Value, Value) throws -> Value), which takes a Sequence of tuples, storing the key-value pairs and a closure, which defines how to handle duplicate keys.

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

Test code:

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]

Upvotes: 3

Related Questions