Reputation: 10139
I have this Swift code for merging two Dictionaries together:
extension Dictionary {
mutating func extend(newVals: Dictionary <String, Any>) {
for (key,value) in newVals {
self.updateValue(value, forKey:key)
}
}
}
The line that contains .updateValue( , forKey:)
generates the following error:
'protocol<>' is not convertible to 'Value'
Previously I had newVals
as a Dictionary <String, String>
and it worked fine, so my guess is the problem is caused by the use of Any
.
My problem here is that I am using Dictionaries with a mixture of String
s and Int
s (and possibly other types of value later on).
Is there anyway to get this extend
function to work with the type Any
?
Upvotes: 0
Views: 225
Reputation: 93276
You don't actually need to (and you can't) specify the Any
type in the function declaration - you need to have the subtypes of the newValues
dictionary match the dictionary it's extending:
extension Dictionary {
mutating func extend(newVals: Dictionary) {
for (key,value) in newVals {
self.updateValue(value, forKey:key)
}
}
}
var dict = ["one": 1, "two": 2, "hello": "goodbye"]
dict.extend(["three": 3])
dict.extend(["foo": "bar"])
Key
and Value
are type aliases within the Dictionary
type that map to the specific key- and value-types of a particular instance.
Upvotes: 2