I want to add another dictionary entry to a dictionary in swift e.g.
let a: [String: Any] = ["Test": 1, "good":false]
let b = a + ["hello": "there"]
print(b)
(Sorry if +
looks crazy here, as that's how Kotlin achieves this. I'm more familiar with Kotlin than Swift.)
But I get the error Binary operator '+' cannot be applied to two '[String : Any]' operands
I can't use updateValue
too
let a: [String: Any] = ["Test": 1, "good":false]
let b = a.updateValue("hello": "there")
print(b)
It will error stating Cannot use mutating member on immutable value: 'a' is a 'let' constant
I can do it by an extension function as per proposed https://stackoverflow.com/a/26728685/3286489
but it looks overkill.
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
}
}
Is there a simple operator I can just add another entry to it to for a new dictionary?
Note: I'm not referring to append as per How to append elements into a dictionary in Swift?, as I receive an immutable dictionary let
that I need to add another entry to it.