慕桂英546537
使用Swift 5,您可以使用以下五个代码段中的一个来解决您的问题。#1。使用Dictionary mapValues(_:)方法let dictionary = ["foo": 1, "bar": 2, "baz": 5]let newDictionary = dictionary.mapValues { value in
return value + 1}//let newDictionary = dictionary.mapValues { $0 + 1 } // also worksprint(newDictionary) // prints: ["baz": 6, "foo": 2, "bar": 3]#2。使用Dictionary map方法和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 workslet newDictionary = Dictionary(uniqueKeysWithValues: tupleArray)print(newDictionary) // prints: ["baz": 6, "foo": 2, "bar": 3]#3。使用Dictionary reduce(_:_:)方法或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。使用Dictionary subscript(_:default:)下标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。使用Dictionary 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]