Swift 4+

Good news! Swift 4 includes a mapValues(_:) method which constructs a copy of a dictionary with the same keys, but different values. It also includes a filter(_:) overload which returns a Dictionary, and init(uniqueKeysWithValues:) and init(_:uniquingKeysWith:) initializers to create a Dictionary from an arbitrary sequence of tuples. That means that, if you want to change both the keys and values, you can say something like:

let newDict = Dictionary(uniqueKeysWithValues:
    oldDict.map { key, value in (key.uppercased(), value.lowercased()) })

There are also new APIs for merging dictionaries together, substituting a default value for missing elements, grouping values (converting a collection into a dictionary of arrays, keyed by the result of mapping the collection over some function), and more.

During discussion of the proposal, SE-0165, that introduced these features, I brought up this Stack Overflow answer several times, and I think the sheer number of upvotes helped demonstrate the demand. So thanks for your help making Swift better!

Answer from Becca Royal-Gordon on Stack Overflow
Top answer
1 of 14
381

Swift 4+

Good news! Swift 4 includes a mapValues(_:) method which constructs a copy of a dictionary with the same keys, but different values. It also includes a filter(_:) overload which returns a Dictionary, and init(uniqueKeysWithValues:) and init(_:uniquingKeysWith:) initializers to create a Dictionary from an arbitrary sequence of tuples. That means that, if you want to change both the keys and values, you can say something like:

let newDict = Dictionary(uniqueKeysWithValues:
    oldDict.map { key, value in (key.uppercased(), value.lowercased()) })

There are also new APIs for merging dictionaries together, substituting a default value for missing elements, grouping values (converting a collection into a dictionary of arrays, keyed by the result of mapping the collection over some function), and more.

During discussion of the proposal, SE-0165, that introduced these features, I brought up this Stack Overflow answer several times, and I think the sheer number of upvotes helped demonstrate the demand. So thanks for your help making Swift better!

2 of 14
141

With Swift 5, you can use one of the five following snippets in order to solve your problem.


#1. Using Dictionary mapValues(_:) method

let dictionary = ["foo": 1, "bar": 2, "baz": 5]

let newDictionary = dictionary.mapValues { value in
    return value + 1
}
//let newDictionary = dictionary.mapValues { $0 + 1 } // also works

print(newDictionary) // prints: ["baz": 6, "foo": 2, "bar": 3]

#2. Using Dictionary map method and init(uniqueKeysWithValues:) initializer

let dictionary = ["foo": 1, "bar": 2, "baz": 5]

let tupleArray = dictionary.map { (key: String, value: Int) in
    return (key, value + 1)
}
//let tupleArray = dictionary.map { (1 + 1) } // also works

let newDictionary = Dictionary(uniqueKeysWithValues: tupleArray)

print(newDictionary) // prints: ["baz": 6, "foo": 2, "bar": 3]

#3. Using Dictionary reduce(_:_:) method or reduce(into:_:) method

let dictionary = ["foo": 1, "bar": 2, "baz": 5]

let newDictionary = dictionary.reduce([:]) { (partialResult: [String: Int], tuple: (key: String, value: Int)) in
    var result = partialResult
    result[tuple.key] = tuple.value + 1
    return result
}

print(newDictionary) // prints: ["baz": 6, "foo": 2, "bar": 3]
let dictionary = ["foo": 1, "bar": 2, "baz": 5]

let newDictionary = dictionary.reduce(into: [:]) { (result: inout [String: Int], tuple: (key: String, value: Int)) in
    result[tuple.key] = tuple.value + 1
}

print(newDictionary) // prints: ["baz": 6, "foo": 2, "bar": 3]

#4. Using Dictionary subscript(_:default:) subscript

let dictionary = ["foo": 1, "bar": 2, "baz": 5]

var newDictionary = [String: Int]()
for (key, value) in dictionary {
    newDictionary[key, default: value] += 1
}

print(newDictionary) // prints: ["baz": 6, "foo": 2, "bar": 3]

#5. Using Dictionary subscript(_:) subscript

let dictionary = ["foo": 1, "bar": 2, "baz": 5]

var newDictionary = [String: Int]()
for (key, value) in dictionary {
    newDictionary[key] = value + 1
}

print(newDictionary) // prints: ["baz": 6, "foo": 2, "bar": 3]
🌐
Apple Developer
developer.apple.com › documentation › swift › dictionary › mapvalues(_:)
mapValues(_:) | Apple Developer Documentation
Returns a new dictionary containing the keys of this dictionary with the values transformed by the given closure.
🌐
Swift Forums
forums.swift.org › evolution › pitches
Mapping Dictionary keys - Pitches - Swift Forums
June 14, 2018 - It would be nice to have mapKeys<T> and compactMapKeys<T> functions for dictionaries, just as we now have mapValues<T> and compactMapValues<T> in Swift 4.0. The motivation behind this is that there are concrete cases wh…
People also ask

What is mapValues in Swift dictionary?
The mapValues function in Swift is used to transform the values in a dictionary. Unlike the map function, mapValues returns a new dictionary with transformed values, and the original keys unchanged.
🌐
dhiwise.com
dhiwise.com › post › exploring-the-intricacies-of-swift-map-dictionary
The Ultimate Swift Map Dictionary Tutorial for Beginners
How to define a map in Swift?
In Swift, you can create a map (also known as a dictionary) by using the following syntax: ```swift var map = [KeyType: ValueType] ``` Where KeyType is the type of value that can be used as a dictionary key, and ValueType is the type of values that the dictionary holds.
🌐
dhiwise.com
dhiwise.com › post › exploring-the-intricacies-of-swift-map-dictionary
The Ultimate Swift Map Dictionary Tutorial for Beginners
How to map dictionary to model in Swift?
You can map a dictionary to a model in Swift by looping over the dictionary and assigning each key-value pair to a property in the model.
🌐
dhiwise.com
dhiwise.com › post › exploring-the-intricacies-of-swift-map-dictionary
The Ultimate Swift Map Dictionary Tutorial for Beginners
🌐
DhiWise
dhiwise.com › post › exploring-the-intricacies-of-swift-map-dictionary
The Ultimate Swift Map Dictionary Tutorial for Beginners
July 10, 2024 - However, this function is not limited to arrays; it can also be used with dictionaries such as Swift dictionary maps. While an array map function transforms and maps the array’s elements, a Swift dictionary map allows us to transform and map both the dictionary’s keys and values.
🌐
TutorialsPoint
tutorialspoint.com › what-s-the-cleanest-way-of-applying-map-to-a-dictionary-in-swift
What\'s the cleanest way of applying map() to a dictionary in Swift?
A powerful higher-order function in Swift called map() enables you to change groups of components in accordance with a closure you supply. The keys, values, or key-value combinations of a dictionary can be changed into a new collection using the map() function when it comes to dictionaries.
🌐
Sarunw
sarunw.com › posts › different-ways-to-map-dictionary-in-swift
Different ways to map over Dictionary in Swift | Sarunw
September 11, 2023 - 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>
🌐
Cocoa Casts
cocoacasts.com › swift-essentials-1-how-to-use-swift-map-to-transforms-arrays-sets-and-dictionaries
How to Use Swift Map to Transform Arrays, Sets, and ...
In this example, we invoke mapValues(_:) on the dictionary of country codes and country names. We transform the value of each key-value pair to an integer, the number of characters of the country name. The result of mapValues(_:) is a dictionary of type [String:Int]. import Foundation let countries = [ "US": "United States", "BE": "Belgium", "CN": "China" ] let ints = countries.mapValues { $0.count } print(ints) What Are the Benefits of the Final Keyword in Swift
Find elsewhere
🌐
Hacking with Swift
hackingwithswift.com › example-code › language › how-to-transform-a-dictionary-using-mapvalues
How to transform a dictionary using mapValues() - free Swift example code and tips
May 28, 2019 - Although dictionaries have a general map() method, they also have a specialized form of map() called mapValues() – it transforms just the values of the dictionary, leaving the keys untouched.
🌐
GitHub
gist.github.com › jordanekay › 3e4f46d9f9e0d50c2b7b
Mapping dictionaries in Swift · GitHub
Save jordanekay/3e4f46d9f9e0d50c2b7b to your computer and use it in GitHub Desktop. Download ZIP · Mapping dictionaries in Swift · Raw · Dictionary.swift · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below.
🌐
GitHub
gist.github.com › pilky › c19ac202c06159b2a63446b3a94c3c7e
Key value mapping for swift dictionaries · GitHub
Save pilky/c19ac202c06159b2a63446b3a94c3c7e to your computer and use it in GitHub Desktop. Download ZIP · Key value mapping for swift dictionaries · Raw · KeyValueMap.swift · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below.
🌐
DhiWise
dhiwise.com › post › navigating-key-value-pairs-with-the-swift-dictionary
Navigating Key-Value Pairs with the Swift Dictionary
July 10, 2024 - However, Swift's dictionary stands out due to its focus on type safety, expressive syntax, and extensive standard library support. A Swift dictionary typically holds unique keys associated with values.
🌐
Medium
karthikmk.medium.com › swift-mapkeys-1662ce12b51c
Swift MapKeys. Map the dictionary keys into a… | by Karthik | Medium
September 29, 2021 - To avoid the unnecessary typos in the query we tend to force the Key into an enum just like Codable CodingKey. New QueryParam Dictionary looks like [ParamKey: Any] The actual problem is when we pass the QueryParam into URLSession. Since URLSession accepts [String: Any], we should map our ParamKeys into String. We were looking for a native api from the swift collection, unfortunately, we couldn’t find one.
🌐
Carver Code
carvercode.com › home › how to map over a dictionary in swift
How to Map Over a Dictionary in Swift - Carver Code
April 9, 2021 - let scores = ["James": 6, "Francisco": ... If you would like you transform only the values of a dictionary, leaving the keys intact, you can use the mapValues(_:) method....
🌐
Codecademy
codecademy.com › learn › learn-swift › modules › learn-swift-dictionaries › cheatsheet
Learn Swift: Dictionaries Cheatsheet | Codecademy
Learn how to build iOS applications with Swift and SwiftUI and publish them to Apples' App Store. ... To assign the value of a key-value pair to a variable, set the value of a variable to dictionaryName[keyValue].
🌐
Lordcodes
lordcodes.com › articles › map-dictionary-keys-to-different-type
Map the keys of a dictionary to a different type | Lord Codes
February 21, 2020 - The Swift standard library includes functions to transform the values of a Dictionary, we need to add one ourselves to do the same to the keys. There are situations this can come in handy such as converting a Dictionary of analytics event parameters from using an internal enum for the keys to using Strings for reporting to our analytics API. This neat little extension will allow us to do just that! extension Dictionary { func mapKeys<NewKeyT>( _ transform: (Key) throws -> NewKeyT ) rethrows -> [NewKeyT: Value] { var newDictionary = [NewKeyT: Value]() try forEach { key, value in let newKey = try transform(key) newDictionary[newKey] = value } return newDictionary } }
🌐
Andy Ibanez
andyibanez.com › posts › understanding-basic-data-structures-dictionaries-in-depth
Understanding Basic Data Structures in Swift: Dictionaries in Depth - Andy Ibanez
January 27, 2021 - In this article we will study this structure which is known by everyone, and we will also learn about its quirks and unknown features. Dictionaries map keys with values. Similar to an array, but instead of using numerical indexes, they use a Hashable as the key.
🌐
Matteo Manferdini
matteomanferdini.com › home › blog › organizing data by key in swift dictionaries
Organizing Data by Key in Swift Dictionaries
June 22, 2023 - In other programming languages, ... hash map, or associative array. Dictionaries are widely used in Swift and help store and access data with logical relationships or structures, such as contact information, product details, settings, or preferences. There are several ways to create a dictionary in Swift. The most straightforward way is to use the literal syntax, which involves writing the key-value pairs inside ...