iNick
iNick

Reputation: 115

Adding integers from a dictionary together

Looking to add together integers from a dictionary. For example:

var dictionary = ["one": 1, "two": 2, "three": 3, "four": 4, "five": 5]

I would want to get the sum of 1+2+3+4+5 = 15

I understand it will probably need a loop something like

 for (n, i) in dictionary {
     *some math function*
 }

any help would be appreciated maybe I'm just over thinking this one?

Upvotes: 2

Views: 153

Answers (1)

Sandeep
Sandeep

Reputation: 21154

You can use reduce:combine: to get the sum.

With Swift 2.0, reduce:Combine: is added to the protocol extension of SequenceType. So, it is available to all SequenceType like Array, Set or Dictionary.

dictionary.reduce(0) {
    sum, item in
    return sum + item.1
}

item inside the closure is tuple representing each (key, value) pair. So, item.0 is key where as item.1 is value.The initial value of the sum is 0, and then each time the iteration takes place, sum is added to the value extracted from dictionary.

You could also write it in short as,

dictionary.reduce(0) { return $0 + $1.1 }

While older version of Swift, it has reduce method with Array only. So, we could first get array and apply reduce:combine to get the sum as,

let a = dictionary.values.array.reduce(0) { return $0 + $1 }

Upvotes: 2

Related Questions