Hodson Hodson - 1 year ago 92
Swift Question

Swift Protocol - Dictionary property with values of any type

I have a protocol with the following property:

var featureSpecificConfigurationDict: [String: Any] { get set }

It's a dictionary that should have a
as the key and can take any type as its value, i.e.

When I try to add a key and value to the dictionary in a class that conforms to the protocol as such:

var featureSpecificConfigurationDict = ["feature-specific-configuration" : "test"]

I get the following build error:

Protocol requires property 'featureSpecificConfigurationDict' with
type '[String : Any]'

along with:

Candidate has non-matching type '[String : String]'

I can cast the
key value to
like below but that seems wrong to me.

var featureSpecificConfigurationDict = ["feature-specific-configuration" : "test" as Any]

So my question is, how do I correctly set a dictionary property in a protocol that accepts a value of any type and then use it in a class that conforms to that protocol.

Answer Source

The compiler is looking at the dictionary you've provided and inferring that it's a [String : String]. If, in your class you declare featureSpecificConfigurationDict as

var featureSpecificConfigurationDict: [String : Any] = ["feature-specific-configuration" : "test"]

it'll realize that you want to be able to store Any type in there, not just those that it found in the initial value, and also conform to your protocol.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download