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?
>Solution :
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.