Different ways to map over Dictionary in Swift

⋅ 3 min read ⋅ Swift Dictionary

Table of Contents

When talking about a map function over a Dictionary, there are many ways to think about it.

You might want to do either one of these three things.

  1. Transform a value, but keep the same key.
  2. Transform a key, but keep the same value.
  3. Transform both key and value.

Swift only supports the first case out of the box.

Transform Value

If you want to transform the value part of a dictionary and keep the same key, you can use mapValues(_:).

The syntax is similar to mapping over an array. We provide a transform closure that accepts a value of the dictionary and returns a transformed value.

func mapValues<T>(_ transform: (Value) throws -> T) rethrows -> Dictionary<Key, T>

In this example, I want to double the integer value of the dictionary.

let dict: [String: Int] = [
"a": 1,
"b": 2,
"c": 3
]

let doubleDict = dict.mapValues { value in
// 1
return value * 2
}

// 2
print(doubleDict)
// ["b": 4, "c": 6, "a": 2]

1 We get a value of each element in the dictionary and return the transformed one from the closure.
2 Beware that Dictionary is not gurantee the order.

You can easily support sarunw.com by checking out this sponsor.

Sponsor sarunw.com and reach thousands of iOS developers.

Transform Key

When I said that Swift only support the transform of dictionary value, it isn't entirely true.

I meant we don't have a dedicated method like mapKeys to do so.

But we can accomplish this by combining two Swift methods.

  1. map(_:): Dictionary's map(_:) method will let you transform each key and value into a new array (Not dictionary).
  2. Dictionary.init(uniqueKeysWithValues:): You can create a new dictionary from an array of key-value pair Tuple with this initializer.

We can use these two methods to transform the key of a dictionary.

In this example, we transform each key to uppercase.

let dict: [String: Int] = [
"a": 1,
"b": 2,
"c": 3
]

// 1
let uppercasedKeyTuple = dict.map { (key, value) in
return (key.uppercased(), value)
}
print(uppercasedKeyTuple)
// [("C", 3), ("B", 2), ("A", 1)]

// 2
let uppercasedKeyDict = Dictionary(uniqueKeysWithValues: uppercasedKeyTuple)

print(uppercasedKeyDict)
// ["C": 3, "A": 1, "B": 2]

1 Transform the dictionary into an array of key-value pairs. This is a place where you transform your key.
2 Create a dictionary out of this new key-value pair.

The first part of the Tuple will become the key of a dictionary, and the second part will become its value.

Caveat

Every key in the key-value pair Tuple must be unique.

If you provide a Tuple with the same key to Dictionary.init(uniqueKeysWithValues:), you will get a runtime error.

The following code will produce "Fatal error: Duplicate values for key: 'A'" error.

let dict = Dictionary(uniqueKeysWithValues: [("A", 1), ("A", 2)])
// Fatal error: Duplicate values for key: 'A'

You can easily support sarunw.com by checking out this sponsor.

Sponsor sarunw.com and reach thousands of iOS developers.

Transform Both Key and Value

We can transform both the key and value of a dictionary using the same method as the transform key.

Instead of transforming only the key path in the map(_:) method, we do it for both key and value.

let dict: [String: Int] = [
"a": 1,
"b": 2,
"c": 3
]

let mapDict = dict.map { (key, value) in
// 1
return (key.uppercased(), value * 2)
}
print(mapDict)
// [("A", 2), ("C", 6), ("B", 4)]

let transformedDict = Dictionary(uniqueKeysWithValues: mapDict)
print(transformedDict)
// ["B": 4, "A": 2, "C": 6]

1 We transform both the key and value here.


Read more article about Swift, Dictionary, or see all available topic

Enjoy the read?

If you enjoy this article, you can subscribe to the weekly newsletter.
Every Friday, you'll get a quick recap of all articles and tips posted on this site. No strings attached. Unsubscribe anytime.

Feel free to follow me on Twitter and ask your questions related to this post. Thanks for reading and see you next time.

If you enjoy my writing, please check out my Patreon https://www.patreon.com/sarunw and become my supporter. Sharing the article is also greatly appreciated.

Become a patron Buy me a coffee Tweet Share
Previous
How to convert Degrees to Radians in Swift

In this article, we will learn different ways to convert Degrees to Radians in iOS.

Next
How to get Root view controller in Swift

In this article, I will show you a quick and dirty way to get a root view controller in an iOS app.

← Home