KeyedDecodingContainerProtocol - Why so many requirements?

The interface for the KeyedDecodingContainer protocol declares a bunch of requirements like such:

func decode(_ type: Bool.Type, forKey key: Self.Key) throws -> Bool
func decode(_ type: String.Type, forKey key: Self.Key) throws -> String
func decode(_ type: Double.Type, forKey key: Self.Key) throws -> Double
// etc.

As well as a generic one:

func decode<T>(_ type: T.Type, forKey key: Self.Key) throws -> T where T : Decodable

Is that done for performance reasons?

I have implemented a return-type-aware generic extension on KeyedDecodingContainer which always defers to the aforementioned generic implementation:

func decode<Value: Decodable>(
    type: Value.Type = Value.self, 
    _ key: Key
) throws -> Value {
    try decode(type, forKey: key)
}

Which allows me to decode anything in the following way:

self.myValue = container.decode(.myValue)
// instead of
self.myValue = container.decode(String.self, forKey: .myValue)

Now, this works fine and all, but upon submitting this extension for code review, one of my colleague raised concerns for defaulting to calling only the generic implementation rather than the statically-typed one (where applicable).

So, my question is, are these concerns valid?

Well, technically all of those are optional because they all have a default implementation that calls through to the corresponding decodeIfPresent(…) method.

I don’t remember the rationale for this design, and AFAICT there’s nothing about it in SE-0166 Swift Archival & Serialization. If you search Swift Forums for SE-0166 there are a bunch of discussion threads for this proposal, and one of them might discuss this explicitly.

Having said that, I think you’re on to something here:

Is that done for performance reasons?

If you think about the encode side of the standard serialisers, they have to use a different syntax for the common types. A generic implementation would need a lot of as? tests, and aren’t great performance-wise.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

KeyedDecodingContainerProtocol - Why so many requirements?
 
 
Q