Reputation: 10139
I am trying to merge together two Dictionaries, both of this type:
var dict = Dictionary<String, Any>
I have been using code like this to merge them:
extension Dictionary {
mutating func extend(with:Dictionary){
for (key,value) in with {
self.updateValue(value, forKey:key)
}
}
}
...
dict.extend(["num":123,"str":"abc","obj":UIColor.blueColor()])
This last line now produces an error:
Cannot convert the expression's type '(with: Dictionary<String, Any>)' to type 'Dictionary<String, NSObject>'
So Ive been trying to solve this by changing the declaration of extend
to:
mutating func extend(with:Dictionary<String, Any>
But this results in this line self.updateValue
in producing this error:
'protocol<>' is not convertible to 'Value'
My best guess here is that .updateValue
is an Objective C method, and Objective C struggles with the Any
data type.
So my next move was to try and convert my <String, Any>
object into a <String, NSObject>
object in the hope that .updateValue
will accept it. However when I try this:
var dict2 = Dictionary<String, NSObject>
Xcode wants to put a semi colon after the NSObject. If I do that it complains about something else. Ive seen this before, it seems like Xcode can tell something is not right, but it cant put its finger on it.
So my issue is this:
<String, Any>
.Anyone have any idea's on how to do this?
Upvotes: 1
Views: 449
Reputation: 72760
The problem is here:
dict.extend(with:["num":123,"str":"abc","obj":UIColor.blueColor()])
^^^^^
the first parameter of class/struct methods has no automatic external name, so you have to call as:
dict.extend(["num":123,"str":"abc","obj":UIColor.blueColor()])
If you want to use the external name, you have to explicitly declare it:
mutating func extend(withDict with:Dictionary) {
^^^^^^^^
or if you want to use the same as the local name:
mutating func extend(# with:Dictionary){
^
Suggested reading: External Parameter Names
This is the code I used for testing:
var dict = Dictionary<String, Any>()
extension Dictionary {
mutating func extend(with:Dictionary){
for (key,value) in with {
self.updateValue(value, forKey:key)
}
}
}
dict.extend(["num":123,"str":"abc","obj":UIColor.blueColor()])
Upvotes: 2