# Developers Planet

Sunay February 2016

### How to Multiply Every Value in a Dictionary in Swift

So, currently I have this dictionary:

``````var data : [Int:Float] = [0:0,1:1,2:1.414,3:2.732,4:2,5:5.236,6:3.469,7:2.693,8:5.828,9:3.201]
``````

I want to create a new dictionary, say "newData." I want "newData" to have the same keys as "data," but I want to multiply every value in "data" by some constant (say "multiple") to get the values in "newData." How can I do this?

Thanks!

Vatsal Manot February 2016

``````var newData = data

for (key, value) in newData
{
newData[key] = value * multiple
}
``````

appzYourLife February 2016

Given

``````let data : [Int:Float] = [0:0,1:1,2:1.414,3:2.732,4:2,5:5.236,6:3.469,7:2.693,8:5.828,9:3.201]
let factor: Float = 2
``````

You can use the `reduce` method

``````let multiplied = data.reduce([Int:Float]()) { (var result, elm) -> [Int:Float] in
result[elm.0] = elm.1 * factor
return result
}
``````

The result.

``````[3: 5.464, 2: 2.828, 4: 4.0, 9: 6.402, 5: 10.472, 6: 6.938, 7: 5.386, 0: 0.0, 8: 11.656, 1: 2.0]
``````

Please ignore the order since Dictionaries do not have one.

## Why this solution is better then a for loop?

The code I am suggesting here does follow the Functional Programming paradigm. There are several advantages over the classic for loop:

1. It's thread safe: since only immutable values are used, you don't have to worry about other threads that could change these values while you are using them.
2. It's faster: under the hood the elements of the results are processed in parallel
3. It's less error prone because it's more declarative: we are describing how the result should be, not how to build it.

sylvanaar February 2016

Another solution based on `map`

``````let dict1 = ["a":1, "b":2, "c":3]
// Make a copy since we don't want to modify the original
var dict2 = dict1
let multiple = 5

dict2.map { (k,v) in dict2[k] = v*multiple }
``````

I did some simple performance testing with a 10000 and 100000 element array the various solutions proposed perform like this

1. For Loop: 10000 elements 1.28 ms, 100000 elements 12.28 ms
2. Map(): 10000 elements 1.24 ms, 100000 elements 12.23 ms
3. Reduce(): 10000 elements 2.36 ms, 100000 elements 17.18 ms

But you don't have a 10000+ element array. It's just worth noting the difference.

#### Post Status

Asked in February 2016
Viewed 3,170 times
Voted 9