Reputation: 299
I am new to Swift and iOS dev. in general. I was wondering how I could sum multiple values from the same key across different dictionaries. e.g. I have
20 dictionaries with the same key value pair [String: AnyObject] e.g. "Height": 20 I want to sum these and calculate the average. EG:
// Example dictionary
let player17: [String: AnyObject] = [
"Name": "Les Clay",
"Height": 42,
"Soccer Experience": true,
"Guardian Name(s)": "Wynonna Brown"
]
//Used any object here as they all go into a big array
Upvotes: 0
Views: 825
Reputation: 59526
Given
let players: [[String:AnyObject]] = ...
here's another approach
let sum = players.flatMap { $0["Height"] as? Int }.reduce(0, combine: +)
If a dictionary doesn't have a valid
Int
value for the"Height"
key then that dictionary is ignored.
Upvotes: 1
Reputation: 726839
You can use reduce
to add numbers up, like this:
let totalHeight = allPlayers.reduce(0) { (p, c) -> Int in
return p + (c["Height"] as! Int)
}
Note: The c["Height"] as! Int
approach requires hard knowledge that "Height"
key is present in every dictionary, and its value is of type Int
. Otherwise, this will produce an exception at run time.
If some of your dictionaries do not have the proper key in them, or contain the value of a different type, you need to pre-filter or use an optional cast, for example
return p + ((c["Height"] as? Int) ?? 0)
Upvotes: 1