Edit: renamed because although I start with a very (too) specific problem the real question it's building up to is: is there a long-term vision for reflection?
With a CaseIterable
CodingKeys
enum and Mirror
I can almost implement a runtime-type-checked version of the compiler-magic Encodable
implementation.
Side note: why would you want to?
The JSON API I'm coding to wasn't designed with type-safety in mind. I can get much tighter types by moving things around, but that means I can't use the compiler-provided
Codable
implementations. If I implementDecodable
by hand, the compiler's all-members-initialized check makes it hard for me to get it wrong: forgetting a member is a compiler error. But there's no corresponding safety-net for theEncodable
implementation: only tests will save me from adding a member (and associated coding key) but not updatingencode(to:Encoder)
to match. Because of this danger I'm looking for utility alternatives to a fully custom implementation for each struct representing an API object.
Almost, but not quite, because from a CodingKey
value I can't get back to the enum case name, which I need to look up the matching value via Mirror(reflecting: myEncodable)
.
enum CodingKeys: String, CodingKey {
case defaultName // default: .stringValue is also the myEncodable member name
case nonDefaultName = "some-other-name" // .stringValue is not the myEncodable name, no access to "nonDefaultName"
}
I would have expected to be able to find the case name somehow via Mirror(reflecting: CodingKeys.nonDefaultName)
but apparently not.
- Am I simply missing something? (I'm still on Xcode 9, btw.)
- If not: is there a deep design problem here, or just an implementation gap? Is there some sense that "reflection is incomplete but we know where we're going?" Reflection manifesto? ABI stability implications?