Swift Dictionary mapValues()

The mapValues() method transforms the dictionary by applying the same operation to each value in the dictionary.

Example

var multiply = ["first": 1, "second": 2, "third": 3]

// multiply each dictionary value by 2 var result = multiply.mapValues({$0 * 2})
print(result) // Output: ["first": 2, "second": 4, "third": 6]

mapValues() Syntax

The syntax of the mapValues() method is:

dictionary.mapValues({transform})

Here, dictionary is an object of the Dictionary class.


mapValues() Parameters

The mapValues() method takes one parameter:

  • transform - a closure body that describes what type of transformation is to be done to each value.

mapValues() Return Value

  • returns a new dictionary that contains the key of dictionary with the new values transformed by the given closure

Example 1: Swift dictionary mapValues()

var number = ["first": 10, "second": 20, "third": 30]

// add 20 to each value var result = number.mapValues({ $0 + 20})
print(result)

Output

["third": 50, "first": 30, "second": 40]

In the above example, we have used the mapValues() method to transform the number dictionary. Notice the closure definition,

{ $0 + 20 }

This is a short-hand closure that adds each value of number by 20.

$0 is the shortcut to mean the first parameter passed into the closure.

Finally, we have printed the new dictionary that contains the key of number with new values associated with each key.


Example 2: Uppercase dictionary Of Strings Using mapValues()

var employees = [1001: "tracy", 1002: "greg", 1003: "Mason"]

// uppercase each value of employees var result = employees.mapValues({ $0.uppercased()})
print(result)

Output

[1002: "GREG", 1001: "TRACY", 1003: "MASON"]

In the above example, we have used the mapValues() and uppercased() methods to transform each value of the employees dictionary.

The uppercased() method converts each string value of a dictionary to uppercase.