Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading