Search code examples
arraysswiftdictionaryswift3

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.


Solution

  • You could also simply iterate over your array of dictionaries.

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