With Swift 5, you can use one of the following five snippets 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 the Dictionary map and init(uniqueKeysWithValues:) method init(uniqueKeysWithValues:)
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 { ($0, $1 + 1) } // also works let newDictionary = Dictionary(uniqueKeysWithValues: tupleArray) print(newDictionary) // prints: ["baz": 6, "foo": 2, "bar": 3]
# 3. Using the Dictionary method reduce(_:_:) or reduce(into:_:) method reduce(into:_:)
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:) index
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]