Encodable
is a protocol, and protocols do not conform to themselves. That is the first issue. To look at it at a more tangible level, the issue is that just because a group of objects are Encodable
doesn't mean they can be encoded in the same way.
[String:String]
gives enough information so that, because the key and the value are Encodable
, the the dictionary is. Here is an example that shows why [String:Encodable]()
can't conform.
Suppose I have Foo
and Bar
:
struct Foo: Encodable {
let myString: String
let myInt: Int
}
struct Bar: Encodable {
let yourString: String
let yourInt: Int
}
Now I have my dictionary:
var dictionary: [String: Encodable] = [:]
dictionary["fooExample"] = Foo(myString: "whatever", myInt: 100)
dictionary["barExample"] = Bar(yourString: "something", yourInt: 20)
We have a dictionary with keys and values that are all Encodable
. If you take a look, though, dictionary["fooExample"]
and dictionary["barExample"]
encode completely differently. So even though values can individually encode, it doesn't mean that the dictionary with those values can encode.