3 回答

TA貢獻1909條經(jīng)驗 獲得超7個贊
Swift 4+
好消息!Swift 4包含一種mapValues(_:)
方法,該方法使用相同的鍵但不同的值構(gòu)造字典的副本。它還包括一個filter(_:)
過載它返回一個Dictionary
,以及init(uniqueKeysWithValues:)
和init(_:uniquingKeysWith:)
初始化來創(chuàng)建一個Dictionary
從元組的任意序列。這意味著,如果您想要更改鍵和值,您可以這樣說:
let newDict = Dictionary(uniqueKeysWithValues: oldDict.map { key, value in (key.uppercased(), value.lowercased()) })
還有用于將字典合并在一起的新API,用缺省元素替換缺省值,對值進行分組(將集合轉(zhuǎn)換為數(shù)組字典,通過將集合映射到某個函數(shù)的結(jié)果來鍵入)等等。
在討論引入這些功能的SE-0165提案時,我多次提出這個Stack Overflow的答案,我認為大量的upvotes有助于證明需求。謝謝你的幫助讓Swift變得更好!

TA貢獻1848條經(jīng)驗 獲得超10個贊
使用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]

TA貢獻1906條經(jīng)驗 獲得超3個贊
雖然這里的大多數(shù)答案都集中在如何映射整個字典(鍵和值)上,但問題實際上只是想映射值。這是一個重要的區(qū)別,因為映射值允許您保證相同數(shù)量的條目,而映射鍵和值可能會導致重復鍵。
這是一個擴展名,mapValues
允許您只映射值。請注意,它還init
使用一系列鍵/值對來擴展字典,這比從數(shù)組初始化更通用:
extension Dictionary { init<S: SequenceType where S.Generator.Element == Element> (_ seq: S) { self.init() for (k,v) in seq { self[k] = v } } func mapValues<T>(transform: Value->T) -> Dictionary<Key,T> { return Dictionary<Key,T>(zip(self.keys, self.values.map(transform))) }}
- 3 回答
- 0 關(guān)注
- 1253 瀏覽
添加回答
舉報