【发布时间】:2020-11-20 00:49:06
【问题描述】:
我想在 swift 中向字典中添加另一个字典条目,例如
let a: [String: Any] = ["Test": 1, "good":false]
let b = a + ["hello": "there"]
print(b)
(抱歉,+ 在这里看起来很疯狂,因为这就是 Kotlin 实现这一点的方式。我对 Kotlin 比对 Swift 更熟悉。)
但我收到错误Binary operator '+' cannot be applied to two '[String : Any]' operands
我也不能使用updateValue
let a: [String: Any] = ["Test": 1, "good":false]
let b = a.updateValue("hello": "there")
print(b)
会报错Cannot use mutating member on immutable value: 'a' is a 'let' constant
我可以按照 https://stackoverflow.com/a/26728685/3286489 的提议通过扩展函数来实现这一点
但它看起来有点矫枉过正。
let b = a.merge(dict: ["hello": "there"])
print(b)
extension Dictionary {
func merge(dict: Dictionary<Key,Value>) -> Dictionary<Key,Value> {
var mutableCopy = self
for (key, value) in dict {
// If both dictionaries have a value for same key, the value of the other dictionary is used.
mutableCopy[key] = value
}
return mutableCopy
}
}
是否有一个简单的运算符,我可以在其中添加另一个条目以用于新字典?
注意:我不是指 How to append elements into a dictionary in Swift? 中的追加,因为我收到了一个不可变字典 let,我需要向其中添加另一个条目。
【问题讨论】:
标签: swift dictionary