Brandon
Brandon

Reputation: 527

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.

Upvotes: 8

Views: 9829

Answers (3)

Keval Vadoliya
Keval Vadoliya

Reputation: 1053

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, +)

Upvotes: 2

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52183

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, +)

Upvotes: 18

eshirima
eshirima

Reputation: 3867

You could also simply iterate over your array of dictionaries.

var totalHeight: Double = Double()

for person in people
{
    totalHeight += Double(person["height"]!)!
}

Upvotes: 4

Related Questions