

Different ways to map over Dictionary in Swift
source link: https://sarunw.com/posts/different-ways-to-map-dictionary-in-swift/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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.
- Transform a value, but keep the same key.
- Transform a key, but keep the same value.
- 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.
map(_:)
: Dictionary'smap(_:)
method will let you transform each key and value into a new array (Not dictionary).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.
Recommend
-
8
Weak Dictionary Values in Swift Weak Dictionary Values in Swift April 14th, 2020 When dealing with dictionaries and arrays in Swift, it's very important to know that any reference types used as a...
-
40
e9d4687e31 swift/
-
11
Different ways to sort an array of strings in Swift How to sort an array of strings There are two ways to sort in Swift, The one that mutates the original array and the one that don't. Both of them...
-
8
Different ways to check if a string contains another string in Swift 11 Jan 2021 ⋅ 8 min read ⋅ Swift
-
10
Different ways to compare string in Swift 08 Jan 2021 ⋅ 3 min read ⋅ Swift St...
-
17
David Cordero Binding a Swift Dictionary to SwiftUI Published on 17 Jun 2021 Creati...
-
9
Different ways to observe properties in Swift 08 August 2021 After I
-
5
Different ways to catch throwing errors from Swift do-catch 09 Aug 2021 ⋅ 9 min read ⋅ Swift Table of...
-
7
NLP algorithm for clustering dictionary word...
-
11
hash function of dictionary has different complexity for int and string hash function of dictionary has different complexity for int...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK