Conform BirdBush to Codable only when its wrapped type is Codable
Closed this issue · 4 comments
You might be able to find some good uses of conditional conformance here: https://github.com/davecom/SwiftGraph
Something like:
extension BirdBush: Codable where U: Codable {
// I forget if the compiler will do the work for you, or if you’ll have to write the conformance yourself
}
Thanks for the suggestion, Zev.
Hey, @hsnetzer,
There’s a subtle issue with the way this is implemented now: BirdBush
only exists where U
is Codable
, which effectively comes to the same problem as before: you can’t use it except with Codable
types. I think you want something like this:
class BirdBush<U> {
...
}
extension BirdBush: Codable where U: Codable {
...
}
This way, you can use BirdBush with any type you want, and if you happen to use it with a Codable
type, it will become Codable
automatically. You can read more about conditional conformance here: https://swift.org/blog/conditional-conformance/
Enjoy 😉
Ah, thanks again! the where clause would probably cause an error when initializing with anything but codable types. I’ll fix this tomorrow.
This implements the conditional conformance we want. As a consequence of adding conformance in an extension, I did have to mark BirdBush as final, which I'm fine with. Otherwise child objects might not actually be codable.