3

I can't get class A to auto-synthesize codability below

protocol MyCodableProtocol: Codable { }

class B: MyCodableProtocol { }

class A: Codable {
    var foo: MyCodableProtocol = B()
}

cannot automatically synthesize 'Encodable' because 'MyCodableProtocol' does not conform to 'Encodable'

I also get the issue in the more simplified problem

class C: Codable {
    var foo: Codable = "foo"
}

Why yields the even more amusing message:

... because 'Codable' (aka 'Decodable & Encodable') does not conform to 'Encodable'

What is going on?

Robert
  • 37,670
  • 37
  • 171
  • 213
  • 2
    The good ol' problem of [protocols not conforming to themselves](https://stackoverflow.com/a/43408193/2976878) :) Think about how decoding into a `Codable` should work, what concrete type should be constructed? – Hamish Feb 09 '18 at 00:02
  • You can see that the issue is indeed what Hamish has already stated, by trying your examples separately with `Decodable` and `Encodable`. Neither can automatically synthesise the protocol stubs, but you can easily make `C` conform to `Encodable`, while you cannot make it conform to `Encodable`, since the `decode` function expects a concrete type to be decoded, which cannot be inferred by the compiler if you declare your variable to be of type `Codable`. – Dávid Pásztor Feb 09 '18 at 00:08
  • 1
    [Protocols not conforming to themselves](https://stackoverflow.com/a/43408193/2976878) is a useful resource, but I am not sure why its been marked as a duplicate. I have given it some thought and figured out why you can not encode an object with protocol properties its not related to a language issue. I was going to answer this but can't because someone has duped it. – Robert Feb 09 '18 at 12:43

0 Answers0