0

I'm trying to JSON encode a single struct member, I know the member conforms to the Encodable protocol, but the compiler complains about it, saying that "Protocol 'Schema' as a type cannot conform to 'Encodable'". the code looks something like this:

protocol Schema { }

struct Foo {
    let a: Schema
}

f = F(a: a)
let jsonData = try JSONEncoder().encode(f.a)

In this case, I know for a fact that a does in fact conform to Encodable, however, I don't know how to enforce this in the Foo struct. I tried changing it so that Foo.a: Encodable but then it complains that protocol Encodable cannot conform to itself.

After reading about this I understand where the error is coming from, there is no way for the compiler to actually be sure that Foo.a conforms to Encodable because downstream struct may add members that are non-codable, at least that is how I understand it.

However, I can't figure out how to tell it that Foo.a conforms to codable.

I tried this: guard let x = f.a as? Encodable else { } but that just results in the same error.

So basically what I want to know is if there is any way to require that implementers of the Schema protocol also conform to Encodable. Currently, all the implementers of Schema are structs, I think I could solve this by changing them to classes and letting them inherit from a base class that is Encodable but I'm not sure, and I would prefer to use structs.

RTXGamer
  • 3,215
  • 6
  • 20
  • 29
Blubber
  • 2,214
  • 1
  • 17
  • 26
  • 2
    Make it `let a: Schema & Encodable` or `protocol Schema: Encodable {}`, and do something similar to the `AnyEncodable` in the second half of [this answer of mine](https://stackoverflow.com/a/67120403/5133585). – Sweeper Nov 11 '21 at 10:29
  • Awesome! Thanks so much, if you make an answer out of this I can upvote it. – Blubber Nov 11 '21 at 10:42

0 Answers0