Currently, Codable cannot be autosynthesized in an extension outside the file declaring the type. See SR-6101, which discusses maybe extending it within the module. Per that issue we seem to lack a comprehensive theory of where this ought to be allowed. We do have a vague intuition that it's bound together with member visibility, which is obviously involved in the autosynthesized conformance.
I'd like to assert it ought to be allowed for C structs (that otherwise contain Codables
). C structs by definition have no private members, so we have no visibility issues. In fact, we have substantially more guarantees about C structs than we do for Swift types (memory layout, etc.)
Moreover, writing conformances for C structs is very tedious, and is substantially similar to the problem that motivated autosynthesis for Swift in the first place. And of course C authors cannot write conformances in the declaring file (or even module), since Codable is a Swift feature and the types are declared in C. So chances are, this falls to you as a random Swift user.
There are some open questions:
- Are C structs a special case, or is it an application of a general theory of allowing conformances on "simple types"? For example, I can see good arguments for C++ types to also want to support Codable, but since C++ types may have private fields it is not as obvious how to support it. For that matter I think Swift
@frozen
types are also an interesting case. - An alternative might be considering autosynthesis of foreign types part of the 'refine for swift' surface area. So we could introduce
__attribute__((swift_equatable))
and so on. I do think pushing Swift features onto C developers is not ideal, but if you take the view that autoconformance is an 'ergonomics' issue it makes some sense.