Jimmery
Jimmery

Reputation: 10139

Merging Dictionaries with multiple Types, or Any / AnyObject Type

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 Strings and Ints (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

Answers (1)

Nate Cook
Nate Cook

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

Related Questions