swift - Adding integers from a dictionary together -


looking add integers dictionary. example:

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

i want sum of 1+2+3+4+5 = 15

i understand need loop like

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

any appreciated maybe i'm on thinking one?

you can use reduce:combine: sum.

with swift 2.0, reduce:combine: added protocol extension of sequencetype. so, available sequencetype array, set or dictionary.

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

item inside closure tuple representing each (key, value) pair. so, item.0 key item.1 value.the initial value of sum 0, , each time iteration takes place, sum added value extracted dictionary.

you write in short as,

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

while older version of swift, has reduce method array only. so, first array , apply reduce:combine sum as,

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

Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

firemonkey - How do I make a beep sound in Android using Delphi and the API? -

jdbc - Not able to establish database connection in eclipse -