Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of values in a dictionary - Swift

So this is just some similar example code below. I am trying to take the heights of all people and add them together so that I can get an average. I can't seem to figure out how to do this with an array of dictionaries. Also I am using Xcode 3.

let people = [
    [
    "name": "John Doe",
    "sex": "Male",
    "height": "183.0"
    ],
    [
    "name": "Jane Doe",
    "sex": "Female",
    "height": "162.0"
    ],
    [
    "name": "Joe Doe",
    "sex": "Male",
    "height": "179.0"
    ],
    [
    "name": "Jill Doe",
    "sex": "Female",
    "height": "167.0"
    ],
]

The below code seems to just create new empty arrays.

var zero = 0.0
var peopleHeights = Double(player["height"]!)
var totalHeights = zero += peopleHeights!

The below code doubles each individual value so not what I am looking for.

var zero = 0.0
var peopleHeights = Double(player["height"]!)
var totalHeights = peopleHeights.map {$0 + $0}

In the below code I get the response: Value of type Double has no member reduce.

var peopleHeights = Double(player["height"]!)
var totalHeights = peopleHeights.reduce(0.0,combine: +)

Any help would be appreciated.

like image 588
Brandon512 Avatar asked Sep 18 '16 00:09

Brandon512


3 Answers

You need to extract height of each person using map. Then you can apply reduce on the list containing the heights:

You should use flatMap (compactMap on Swift 4+) over map as + works only on unwrapped values.

people.flatMap({ Double($0["height"]!) }).reduce(0, +)

Swift 5

people.compactMap { Double($0["height"]!) }.reduce(0, +)
like image 184
Ozgur Vatansever Avatar answered Sep 29 '22 17:09

Ozgur Vatansever


You could also simply iterate over your array of dictionaries.

var totalHeight: Double = Double()

for person in people
{
    totalHeight += Double(person["height"]!)!
}
like image 28
eshirima Avatar answered Sep 30 '22 17:09

eshirima


compactMap is good to use for the sum of values as it considers only non-nil values.

let totalHeights = people.compactMap { $0["height"] as? Double}.reduce(0, +)
like image 34
keval Avatar answered Sep 27 '22 17:09

keval