Home > Enterprise >  How to add value from Dictionary having value as dictionary in Swift?
How to add value from Dictionary having value as dictionary in Swift?

Time:03-02

I am having dictionary whose value is another dictionary

for ex. ["1": ["1623699578": 1.08], "2": ["1216047930": 6.81]]

inner dictionary will have only one value

i want to do sum of 1.08 and 6.81

for now i am tried to just iterate dictionary and taking value using dict.values.first and adding. But i not sure if its best way

is there any best way to do this?

CodePudding user response:

This will sum all the dictionary value's values. We use reduce to combine the dictionary collections into a single value.

Code:

let dict = ["1": ["1623699578": 1.08], "2": ["1216047930": 6.81]]

let sum: Double = dict.reduce(into: 0) { partialResult, pair in
    partialResult  = pair.value.values.reduce(0,  )
}

print(sum)

This will also sum the inner-dictionary values.

CodePudding user response:

Another notation for what @George proposed can be:

let sum = dict.values.compactMap { $0.values.first }.reduce(0.0) { $0   $1 }
  • Related