[swift-evolution] [Proposal] Foundation Swift Archival & Serialization

Ben Rimmington me at benrimmington.com
Thu Mar 23 14:37:54 CDT 2017


> On 22 Mar 2017, at 17:41, Itai Ferber wrote:
> 
> What’s the use case that you were thinking of? KeyPaths could be useful in the case where you don’t need to customize your key names, but cannot represent a custom case like
> 
> public struct Post {
>     var authorID: Int
>     var bodyText: String
> 
>     private enum CodingKeys : String, CodingKey {
>         case authorID = "author_id"
>         case bodyText = "body_text"
>     }
> }
> Or am I misunderstanding?
> 

For custom names, the `CodingKeys` enum does seem like the best design, unless an attribute can be used.

	public struct Post : Codable {
	    @codable(name: "author_id") var authorID: Int
	    @codable(name: "body_text") var bodyText: String
	}

If each `KeyPath` encapsulates the type information, the `decode` methods won't need a `type` parameter.

	/// Primitive decoding methods (for single-value and keyed containers).
	open class DecodingContainer<Root : Codable> {
	    open func decode(for keyPath: KeyPath<Root, Bool>)   throws -> Bool
	    open func decode(for keyPath: KeyPath<Root, Int>)    throws -> Int
	    open func decode(for keyPath: KeyPath<Root, UInt>)   throws -> UInt
	    open func decode(for keyPath: KeyPath<Root, Float>)  throws -> Float
	    open func decode(for keyPath: KeyPath<Root, Double>) throws -> Double
	    open func decode(for keyPath: KeyPath<Root, String>) throws -> String
	    open func decode(for keyPath: KeyPath<Root, Data>)   throws -> Data
	}

	/// Keyed containers inherit the primitive decoding methods.
	open class KeyedDecodingContainer : DecodingContainer {
	    open func decode<Value : Codable>(for keyPath: KeyPath<Root, Value>) throws -> Value
	}

-- Ben

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170323/959baae6/attachment.html>


More information about the swift-evolution mailing list