0

I want to implement a container type that conforms to Codable, but am running into a bit of an issue. I want to genericize my container to hold any element that can be Encodable & Decodable. Initially, I had this:

struct Container: Codable {
    var identifier: String
    var element: Any
}

...but changed it so that I could have some sort of type safety. Can someone explain what exactly is going on here?

My Code

struct Container: Codable {
    var identifier: String
    var element: Codable
}

Compiler Output

Playground execution failed:

MyPlayground.playground:3:9: note: cannot automatically synthesize 'Decodable' because 'Codable' (aka 'Decodable & Encodable') does not conform to 'Decodable'
    var element: Codable
...
72A12F4E
  • 1,744
  • 1
  • 14
  • 28
  • Protocols don't conform to themselves, so `Codable` doesn't conform to `Codable`, therefore as not all properties of your type conform to `Codable`, you don't get an auto-generated conformance. Consider – what concrete type should Swift decode into for the `element` property? – Hamish Jun 12 '17 at 18:34
  • Compare also https://stackoverflow.com/questions/44480667/jsonencoder-works-for-stringstring-fails-for-stringcodable – Hamish Jun 12 '17 at 18:37

0 Answers0