Hodson
Hodson

Reputation: 3556

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 String as the key and can take any type as its value, i.e. String, Int, Bool etc

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 String key value to Any 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.

Upvotes: 0

Views: 1019

Answers (3)

gnasher729
gnasher729

Reputation: 52538

String might be compatible with "Any", but [String:String] is not compatible with [String:Any]. Write

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

Upvotes: 1

Casey Fleser
Casey Fleser

Reputation: 5787

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.

Upvotes: 1

Alexander Zimin
Alexander Zimin

Reputation: 1710

When you write var featureSpecificConfigurationDict = ["feature-specific-configuration" : "test"] you give typecast job to the right side. So compiler thinking that it's [String: String], you should handle type on the left side, so declare this with:

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

Upvotes: 1

Related Questions