<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/xhtml; charset=utf-8">
</head>
<body>
<div style="font-family:sans-serif"><div style="white-space:normal">
<p dir="auto">Thanks Joe, and thanks for passing this along!</p>
<p dir="auto">To those who are curious, we use abstract base classes for a cascading list of reasons:</p>
<ul>
<li>We need to be able to represent keyed encoding and decoding containers as abstract types which are generic on a key type</li>
<li>There are two ways to support abstraction in this way: protocol & type constraints, and generic types
<ul>
<li>Since Swift protocols are not generic, we unfortunately cannot write <code style="background-color:#F7F7F7; border-radius:3px; margin:0; padding:0 0.4em" bgcolor="#F7F7F7">protocol KeyedEncodingContainer<Key : CodingKey> { ... }</code>, which is the "ideal" version of what we're trying to represent</li>
</ul></li>
<li><p dir="auto">Let's try this with a protocol first (simplified here):</p>
<pre style="background-color:#F7F7F7; border-radius:5px 5px 5px 5px; margin-left:15px; margin-right:15px; max-width:90vw; overflow-x:auto; padding:5px" bgcolor="#F7F7F7"><code style="background-color:#F7F7F7; border-radius:3px; margin:0; padding:0" bgcolor="#F7F7F7">protocol Container {
associatedtype Key : CodingKey
}
func container<Key : CodingKey, Cont : Container>(_ type: Key.Type) -> Cont where Cont.Key == Key {
// return something
}
</code></pre>
<p dir="auto">This looks promising so far — let's try to make it concrete:</p>
<pre style="background-color:#F7F7F7; border-radius:5px 5px 5px 5px; margin-left:15px; margin-right:15px; max-width:90vw; overflow-x:auto; padding:5px" bgcolor="#F7F7F7"><code style="background-color:#F7F7F7; border-radius:3px; margin:0; padding:0" bgcolor="#F7F7F7">struct ConcreteContainer<K : CodingKey> : Container {
typealias Key = K
}
func container<Key : CodingKey, Cont : Container>(_ type: Key.Type) -> Cont where Cont.Key == Key {
return ConcreteContainer<Key>() // error: Cannot convert return expression of type 'ConcreteContainer<Key>' to return type 'Cont'
}
</code></pre>
<p dir="auto">Joe or anyone from the Swift team can describe this better, but this is my poor-man's explanation of why this happens. Swift's type constraints are "directional" in a sense. You can constrain a type going <em>into</em> a function, but not <em>out of</em> a function. There is no type I could return from inside of <code style="background-color:#F7F7F7; border-radius:3px; margin:0; padding:0 0.4em" bgcolor="#F7F7F7">container()</code> which would satisfy this constraint, because the constraint can only be satisfied by turning <code style="background-color:#F7F7F7; border-radius:3px; margin:0; padding:0 0.4em" bgcolor="#F7F7F7">Cont</code> into a concrete type from the <em>outside</em>.</p>
<p dir="auto">Okay, well let's try this:</p>
<pre style="background-color:#F7F7F7; border-radius:5px 5px 5px 5px; margin-left:15px; margin-right:15px; max-width:90vw; overflow-x:auto; padding:5px" bgcolor="#F7F7F7"><code style="background-color:#F7F7F7; border-radius:3px; margin:0; padding:0" bgcolor="#F7F7F7">func container... {
return ConcreteContainer<Key>() as! Cont
}
</code></pre>
<p dir="auto">This compiles fine! Hmm, let's try to use it:</p>
<pre style="background-color:#F7F7F7; border-radius:5px 5px 5px 5px; margin-left:15px; margin-right:15px; max-width:90vw; overflow-x:auto; padding:5px" bgcolor="#F7F7F7"><code style="background-color:#F7F7F7; border-radius:3px; margin:0; padding:0" bgcolor="#F7F7F7">container(Int.self) // error: Generic parameter 'Cont' could not be inferred
</code></pre>
<p dir="auto">The type constraint can only be fulfilled from the outside, not the inside. The function call itself has no context for the concrete type that this would return, so this is a no-go.</p></li>
<li><p dir="auto">If we can't do it with type constraints in this way, is it possible with generic types? Yep! Generic types satisfy this without a problem. However, since we don't have generic protocols, we have to use a generic abstract base class to represent the same concept — an abstract container generic on the type of key which dynamically dispatches to the "real" subclassed type</p></li>
</ul>
<p dir="auto">Hopes that gives some simplified insight into the nature of this decision.</p>
<p dir="auto">On 15 Mar 2017, at 18:18, Joe Groff wrote:</p>
<p dir="auto"></p></div>
<div style="white-space:normal"><blockquote style="border-left:2px solid #777; color:#777; margin:0 0 5px; padding-left:5px"><p dir="auto">Congrats on getting this out! A question from the field:<br>
<br>
<a href="https://twitter.com/mdiep/status/842178457115230210" style="color:#777">https://twitter.com/mdiep/status/842178457115230210</a> Why does the Swift Serialization API proposal use abstract base classes?<br>
<br>
-Joe<br>
<br>
</p>
<blockquote style="border-left:2px solid #777; color:#999; margin:0 0 5px; padding-left:5px; border-left-color:#999"><p dir="auto">On Mar 15, 2017, at 3:40 PM, Itai Ferber via swift-evolution <swift-evolution@swift.org> wrote:<br>
<br>
Hi everyone,<br>
<br>
The following introduces a new Swift-focused archival and serialization API as part of the Foundation framework. We’re interested in improving the experience and safety of performing archival and serialization, and are happy to receive community feedback on this work.<br>
Because of the length of this proposal, the Appendix and Alternatives Considered sections have been omitted here, but are available in the full proposal on the swift-evolution repo. The full proposal also includes an Unabridged API for further consideration.<br>
<br>
Without further ado, inlined below.<br>
<br>
— Itai<br>
<br>
Swift Archival & Serialization<br>
        • Proposal: SE-NNNN<br>
        • Author(s): Itai Ferber, Michael LeHew, Tony Parker<br>
        • Review Manager: TBD<br>
        • Status: Awaiting review<br>
        • Associated PRs:<br>
                • #8124<br>
                • #8125<br>
Introduction<br>
Foundation's current archival and serialization APIs (NSCoding, NSJSONSerialization, NSPropertyListSerialization, etc.), while fitting for the dynamism of Objective-C, do not always map optimally into Swift. This document lays out the design of an updated API that improves the developer experience of performing archival and serialization in Swift.<br>
<br>
Specifically:<br>
<br>
        • It aims to provide a solution for the archival of Swift struct and enum types<br>
        • It aims to provide a more type-safe solution for serializing to external formats, such as JSON and plist<br>
Motivation<br>
The primary motivation for this proposal is the inclusion of native Swift enum and struct types in archival and serialization. Currently, developers targeting Swift cannot participate in NSCoding without being willing to abandon enum and structtypes — NSCoding is an @objc protocol, conformance to which excludes non-class types. This is can be limiting in Swift because small enums and structs can be an idiomatic approach to model representation; developers who wish to perform archival have to either forgo the Swift niceties that constructs like enumsprovide, or provide an additional compatibility layer between their "real" types and their archivable types.<br>
<br>
Secondarily, we would like to refine Foundation's existing serialization APIs (NSJSONSerialization and NSPropertyListSerialization) to better match Swift's strong type safety. From experience, we find that the conversion from the unstructured, untyped data of these formats into strongly-typed data structures is a good fit for archival mechanisms, rather than taking the less safe approach that 3rd-party JSON conversion approaches have taken (described further in an appendix below).<br>
<br>
We would like to offer a solution to these problems without sacrificing ease of use or type safety.<br>
<br>
Agenda<br>
This proposal is the first stage of three that introduce different facets of a whole Swift archival and serialization API:<br>
<br>
        • This proposal describes the basis for this API, focusing on the protocols that users adopt and interface with<br>
        • The next stage will propose specific API for new encoders<br>
        • The final stage will discuss how this new API will interop with NSCoding as it is today<br>
SE-NNNN provides stages 2 and 3.<br>
<br>
Proposed solution<br>
We will be introducing the following new types:<br>
<br>
        • protocol Codable: Adopted by types to opt into archival. Conformance may be automatically derived in cases where all properties are also Codable.<br>
        • protocol CodingKey: Adopted by types used as keys for keyed containers, replacing String keys with semantic types. Conformance may be automatically derived in most cases.<br>
        • protocol Encoder: Adopted by types which can take Codable values and encode them into a native format.<br>
                • class KeyedEncodingContainer<Key : CodingKey>: Subclasses of this type provide a concrete way to store encoded values by CodingKey. Types adopting Encoder should provide subclasses of KeyedEncodingContainer to vend.<br>
                • protocol SingleValueEncodingContainer: Adopted by types which provide a concrete way to store a single encoded value. Types adopting Encoder should provide types conforming to SingleValueEncodingContainer to vend (but in many cases will be able to conform to it themselves).<br>
        • protocol Decoder: Adopted by types which can take payloads in a native format and decode Codable values out of them.<br>
                • class KeyedDecodingContainer<Key : CodingKey>: Subclasses of this type provide a concrete way to retrieve encoded values from storage by CodingKey. Types adopting Decoder should provide subclasses of KeyedDecodingContainer to vend.<br>
                • protocol SingleValueDecodingContainer: Adopted by types which provide a concrete way to retrieve a single encoded value from storage. Types adopting Decoder should provide types conforming to SingleValueDecodingContainer to vend (but in many cases will be able to conform to it themselves).<br>
For end users of this API, adoption will primarily involve the Codable and CodingKey protocols. In order to participate in this new archival system, developers must add Codable conformance to their types:<br>
<br>
// If all properties are Codable, implementation is automatically derived:<br>
public struct Location : Codable {<br>
<br>
<br>
public let latitude: Double<br>
<br>
<br>
public let longitude: Double<br>
}<br>
<br>
<br>
<br>
public enum Animal : Int, Codable {<br>
<br>
<br>
case chicken = 1<br>
<br>
<br>
case<br>
dog<br>
<br>
case<br>
turkey<br>
<br>
case<br>
cow<br>
<br>
}<br>
<br>
<br>
<br>
public struct Farm : Codable {<br>
<br>
<br>
public let name: String<br>
<br>
<br>
public let location: Location<br>
<br>
<br>
public let animals: [Animal]<br>
}<br>
With developer participation, we will offer encoders and decoders (described in SE-NNNN, not here) that take advantage of this conformance to offer type-safe serialization of user models:<br>
<br>
let farm = Farm(name: "Old MacDonald's Farm",<br>
<br>
location<br>
: Location(latitude: 51.621648, longitude: 0.269273),<br>
<br>
animals<br>
: [.chicken, .dog, .cow, .turkey, .dog, .chicken, .cow, .turkey, .dog])<br>
let payload: Data = try JSONEncoder().encode(farm)<br>
<br>
<br>
<br>
do {<br>
<br>
<br>
let farm = try JSONDecoder().decode(Farm.self, from: payload)<br>
<br>
<br>
<br>
// Extracted as user types:<br>
<br>
<br>
let coordinates = "\(farm.location.latitude, farm.location.longitude)"<br>
} catch {<br>
<br>
<br>
// Encountered error during deserialization<br>
}<br>
This gives developers access to their data in a type-safe manner and a recognizable interface.<br>
<br>
Detailed design<br>
To support user types, we expose the Codable protocol:<br>
<br>
/// Conformance to `Codable` indicates that a type can marshal itself into and out of an external representation.<br>
public protocol Codable {<br>
<br>
<br>
/// Initializes `self` by decoding from `decoder`.<br>
<br>
<br>
///<br>
<br>
<br>
/// - parameter decoder: The decoder to read data from.<br>
<br>
<br>
/// - throws: An error if reading from the decoder fails, or if read data is corrupted or otherwise invalid.<br>
<br>
<br>
init(from decoder: Decoder) throws<br>
<br>
<br>
<br>
/// Encodes `self` into the given encoder.<br>
<br>
<br>
///<br>
<br>
<br>
/// If `self` fails to encode anything, `encoder` will encode an empty `.default` container in its place.<br>
<br>
<br>
///<br>
<br>
<br>
/// - parameter encoder: The encoder to write data to.<br>
<br>
<br>
/// - throws: An error if any values are invalid for `encoder`'s format.<br>
<br>
<br>
func encode(to encoder: Encoder) throws<br>
}<br>
By adopting Codable, user types opt in to this archival system.<br>
<br>
Structured types (i.e. types which encode as a collection of properties) encode and decode their properties in a keyed manner. Keys may be String-convertible or Int-convertible (or both), and user types which have properties should declare semantic key enums which map keys to their properties. Keys must conform to the CodingKey protocol:<br>
<br>
/// Conformance to `CodingKey` indicates that a type can be used as a key for encoding and decoding.<br>
public protocol CodingKey {<br>
<br>
<br>
/// The string to use in a named collection (e.g. a string-keyed dictionary).<br>
<br>
<br>
var stringValue: String? { get }<br>
<br>
<br>
<br>
/// Initializes `self` from a string.<br>
<br>
<br>
///<br>
<br>
<br>
/// - parameter stringValue: The string value of the desired key.<br>
<br>
<br>
/// - returns: An instance of `Self` from the given string, or `nil` if the given string does not correspond to any instance of `Self`.<br>
<br>
<br>
init?(stringValue: String)<br>
<br>
<br>
<br>
/// The int to use in an indexed collection (e.g. an int-keyed dictionary).<br>
<br>
<br>
var intValue: Int? { get }<br>
<br>
<br>
<br>
/// Initializes `self` from an integer.<br>
<br>
<br>
///<br>
<br>
<br>
/// - parameter intValue: The integer value of the desired key.<br>
<br>
<br>
/// - returns: An instance of `Self` from the given integer, or `nil` if the given integer does not correspond to any instance of `Self`.<br>
<br>
<br>
init?(intValue: Int)<br>
}<br>
For most types, String-convertible keys are a reasonable default; for performance, however, Int-convertible keys are preferred, and Encoders may choose to make use of Ints over Strings. Framework types should provide keys which have both for flexibility and performance across different types of Encoders. It is generally an error to provide a key which has neither a stringValue nor an intValue.<br>
<br>
By default, CodingKey conformance can be derived for enums which have either String or Int backing:<br>
<br>
enum Keys1 : CodingKey {<br>
<br>
<br>
case a // (stringValue: "a", intValue: nil)<br>
<br>
<br>
case b // (stringValue: "b", intValue: nil)<br>
}<br>
<br>
<br>
<br>
enum Keys2 : String, CodingKey {<br>
<br>
<br>
case c = "foo" // (stringValue: "foo", intValue: nil)<br>
<br>
<br>
case d // (stringValue: "d", intValue: nil)<br>
}<br>
<br>
<br>
<br>
enum Keys3 : Int, CodingKey {<br>
<br>
<br>
case e = 4 // (stringValue: "e", intValue: 4)<br>
<br>
<br>
case f // (stringValue: "f", intValue: 5)<br>
<br>
<br>
case g = 9 // (stringValue: "g", intValue: 9)<br>
}<br>
Coding keys which are not enums, have associated values, or have other raw representations must implement these methods manually.<br>
<br>
In addition to automatic CodingKey conformance derivation for enums, Codableconformance can be automatically derived for certain types as well:<br>
<br>
        • Types whose properties are all either Codable or primitive get an automatically derived String-backed CodingKeys enum mapping properties to case names<br>
        • Types falling into (1) and types which provide a CodingKeys enum (directly or via a typealias) whose case names map to properties which are all Codableget automatic derivation of init(from:) and encode(to:) using those properties and keys. Types may choose to provide a custom init(from:) or encode(to:) (or both); whichever they do not provide will be automatically derived<br>
        • Types which fall into neither (1) nor (2) will have to provide a custom key type and provide their own init(from:) and encode(to:)<br>
Many types will either allow for automatic derivation of all codability (1), or provide a custom key subset and take advantage of automatic method derivation (2).<br>
<br>
Encoding and Decoding<br>
<br>
Types which are encodable encode their data into a container provided by their Encoder:<br>
<br>
/// An `Encoder` is a type which can encode values into a native format for external representation.<br>
public protocol Encoder {<br>
<br>
<br>
/// Populates `self` with an encoding container (of `.default` type) and returns it, keyed by the given key type.<br>
<br>
<br>
///<br>
<br>
<br>
/// - parameter type: The key type to use for the container.<br>
<br>
<br>
/// - returns: A new keyed encoding container.<br>
<br>
<br>
/// - precondition: May not be called after a previous `self.container(keyedBy:)` call of a different `EncodingContainerType`.<br>
<br>
<br>
/// - precondition: May not be called after a value has been encoded through a prior `self.singleValueContainer()` call.<br>
<br>
<br>
func container<Key : CodingKey>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key><br>
<br>
<br>
<br>
/// Returns an encoding container appropriate for holding a single primitive value.<br>
<br>
<br>
///<br>
<br>
<br>
/// - returns: A new empty single value container.<br>
<br>
<br>
/// - precondition: May not be called after a prior `self.container(keyedBy:)` call.<br>
<br>
<br>
/// - precondition: May not be called after a value has been encoded through a previous `self.singleValueContainer()` call.<br>
<br>
<br>
func singleValueContainer() -> SingleValueEncodingContainer<br>
<br>
<br>
<br>
/// The path of coding keys taken to get to this point in encoding.<br>
<br>
<br>
var codingKeyContext: [CodingKey] { get }<br>
}<br>
<br>
<br>
<br>
// Continuing examples from before; below is automatically generated by the compiler if no customization is needed.<br>
public struct Location : Codable {<br>
<br>
<br>
private enum CodingKeys : CodingKey {<br>
<br>
<br>
case<br>
latitutude<br>
<br>
case<br>
longitude<br>
<br>
}<br>
<br>
<br>
<br>
public func encode(to encoder: Encoder) throws {<br>
<br>
<br>
// Generic keyed encoder gives type-safe key access: cannot encode with keys of the wrong type.<br>
<br>
<br>
let container = encoder.container(keyedBy: CodingKeys.self)<br>
<br>
<br>
<br>
// The encoder is generic on the key -- free key autocompletion here.<br>
<br>
<br>
try container.encode(latitude, forKey: .latitude)<br>
<br>
<br>
try container.encode(longitude, forKey: .longitude)<br>
<br>
<br>
}<br>
}<br>
<br>
<br>
<br>
public struct Farm : Codable {<br>
<br>
<br>
private enum CodingKeys : CodingKey {<br>
<br>
<br>
case<br>
name<br>
<br>
case<br>
location<br>
<br>
case<br>
animals<br>
<br>
}<br>
<br>
<br>
<br>
public func encode(to encoder: Encoder) throws {<br>
<br>
<br>
let container = encoder.container(keyedBy: CodingKeys.self)<br>
<br>
<br>
try container.encode(name, forKey: .name)<br>
<br>
<br>
try container.encode(location, forKey: .location)<br>
<br>
<br>
try container.encode(animals, forKey: .animals)<br>
<br>
<br>
}<br>
}<br>
Similarly, decodable types initialize from data read from their Decoder's container:<br>
<br>
/// A `Decoder` is a type which can decode values from a native format into in-memory representations.<br>
public protocol Decoder {<br>
<br>
<br>
/// Returns the data stored in `self` as represented in a container keyed by the given key type.<br>
<br>
<br>
///<br>
<br>
<br>
/// - parameter type: The key type to use for the container.<br>
<br>
<br>
/// - returns: A keyed decoding container view into `self`.<br>
<br>
<br>
/// - throws: `CocoaError.coderTypeMismatch` if the encountered stored value is not a keyed container.<br>
<br>
<br>
func container<Key : CodingKey>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key><br>
<br>
<br>
<br>
/// Returns the data stored in `self` as represented in a container appropriate for holding a single primitive value.<br>
<br>
<br>
///<br>
<br>
<br>
/// - returns: A single value container view into `self`.<br>
<br>
<br>
/// - throws: `CocoaError.coderTypeMismatch` if the encountered stored value is not a single value container.<br>
<br>
<br>
func singleValueContainer() throws -> SingleValueDecodingContainer<br>
<br>
<br>
<br>
/// The path of coding keys taken to get to this point in decoding.<br>
<br>
<br>
var codingKeyContext: [CodingKey] { get }<br>
}<br>
<br>
<br>
<br>
// Continuing examples from before; below is automatically generated by the compiler if no customization is needed.<br>
public struct Location : Codable {<br>
<br>
<br>
public init(from decoder: Decoder) throws {<br>
<br>
<br>
let container = try decoder.container(keyedBy: CodingKeys.self)<br>
<br>
latitude<br>
= try container.decode(Double.self, forKey: .latitude)<br>
<br>
longitude<br>
= try container.decode(Double.self, forKey: .longitude)<br>
<br>
<br>
}<br>
}<br>
<br>
<br>
<br>
public struct Farm : Codable {<br>
<br>
<br>
public init(from decoder: Decoder) throws {<br>
<br>
<br>
let container = try decoder.container(keyedBy: CodingKeys.self)<br>
<br>
name<br>
= try container.decode(String.self, forKey: .name)<br>
<br>
location<br>
= try container.decode(Location.self, forKey: .location)<br>
<br>
animals<br>
= try container.decode([Animal].self, forKey: .animals)<br>
<br>
<br>
}<br>
}<br>
Keyed Encoding Containers<br>
<br>
Keyed encoding containers are the primary interface that most Codable types interact with for encoding and decoding. Through these, Codable types have strongly-keyed access to encoded data by using keys that are semantically correct for the operations they want to express.<br>
<br>
Since semantically incompatible keys will rarely (if ever) share the same key type, it is impossible to mix up key types within the same container (as is possible with Stringkeys), and since the type is known statically, keys get autocompletion by the compiler.<br>
<br>
/// `KeyedEncodingContainer` is a generic abstract base class that provides a view into an `Encoders` storage and is used to hold the encoded properties of a `Codable` type.<br>
///<br>
/// Encoders should provide subclasses of `KeyedEncodingContainer` for their format.<br>
<br>
open<br>
class KeyedEncodingContainer<Key : CodingKey> {<br>
<br>
<br>
/// Encodes the given value for the given key.<br>
<br>
<br>
///<br>
<br>
<br>
/// - parameter value: The value to encode.<br>
<br>
<br>
/// - parameter key: The key to associate the value with.<br>
<br>
<br>
/// - throws: `CocoaError.coderInvalidValue` if the given value is invalid in the current context for this format.<br>
<br>
<br>
/// - precondition: The key must have a `stringValue` or `intValue` appropriate for the encoding container type.<br>
<br>
open<br>
func encode<Value : Codable>(_ value: Value?, forKey key: Key) throws<br>
<br>
<br>
<br>
/// Encodes the given value for the given key.<br>
<br>
<br>
///<br>
<br>
<br>
/// - parameter value: The value to encode.<br>
<br>
<br>
/// - parameter key: The key to associate the value with.<br>
<br>
<br>
/// - throws: `CocoaError.coderInvalidValue` if the given value is invalid in the current context for this format.<br>
<br>
<br>
/// - precondition: The key must have a `stringValue` or `intValue` appropriate for the encoding container type.<br>
<br>
open<br>
func encode(_ value: Bool?, forKey key: Key) throws<br>
<br>
open<br>
func encode(_ value: Int?, forKey key: Key) throws<br>
<br>
open<br>
func encode(_ value: Int8?, forKey key: Key) throws<br>
<br>
open<br>
func encode(_ value: Int16?, forKey key: Key) throws<br>
<br>
open<br>
func encode(_ value: Int32?, forKey key: Key) throws<br>
<br>
open<br>
func encode(_ value: Int64?, forKey key: Key) throws<br>
<br>
open<br>
func encode(_ value: UInt?, forKey key: Key) throws<br>
<br>
open<br>
func encode(_ value: UInt8?, forKey key: Key) throws<br>
<br>
open<br>
func encode(_ value: UInt16?, forKey key: Key) throws<br>
<br>
open<br>
func encode(_ value: UInt32?, forKey key: Key) throws<br>
<br>
open<br>
func encode(_ value: UInt64?, forKey key: Key) throws<br>
<br>
open<br>
func encode(_ value: Float?, forKey key: Key) throws<br>
<br>
open<br>
func encode(_ value: Double?, forKey key: Key) throws<br>
<br>
open<br>
func encode(_ value: String?, forKey key: Key) throws<br>
<br>
open<br>
func encode(_ value: Data?, forKey key: Key) throws<br>
<br>
<br>
<br>
/// Encodes the given object weakly for the given key.<br>
<br>
<br>
///<br>
<br>
<br>
/// For `Encoder`s that implement this functionality, this will only encode the given object and associate it with the given key if it encoded unconditionally elsewhere in the archive (either previously or in the future).<br>
<br>
<br>
///<br>
<br>
<br>
/// For formats which don't support this feature, the default implementation encodes the given object unconditionally.<br>
<br>
<br>
///<br>
<br>
<br>
/// - parameter object: The object to encode.<br>
<br>
<br>
/// - parameter key: The key to associate the object with.<br>
<br>
<br>
/// - throws: `CocoaError.coderInvalidValue` if the given value is invalid in the current context for this format.<br>
<br>
<br>
/// - precondition: The key must have a `stringValue` or `intValue` appropriate for the encoding container type.<br>
<br>
open<br>
func encodeWeak<Object : AnyObject & Codable>(_ object: Object?, forKey key: Key) throws<br>
<br>
<br>
<br>
/// The path of coding keys taken to get to this point in encoding.<br>
<br>
open<br>
var codingKeyContext: [CodingKey]<br>
}<br>
<br>
<br>
<br>
/// `KeyedDecodingContainer` is a generic abstract base class that provides a view into an `Decoders` storage and is used to hold the encoded properties of a `Codable` type.<br>
///<br>
/// Decoders should provide subclasses of `KeyedDecodingContainer` for their format.<br>
<br>
open<br>
class KeyedDecodingContainer<Key : CodingKey> {<br>
<br>
<br>
/// All the keys the `Decoder` has for this container.<br>
<br>
<br>
///<br>
<br>
<br>
/// Different keyed containers from the same `Decoder` may return different keys here; it is possible to encode with multiple key types which are not convertible to one another. This should report all keys present which are convertible to the requested type.<br>
<br>
open<br>
var allKeys: [Key]<br>
<br>
<br>
<br>
/// Returns whether the `Decoder` contains a value associated with the given key.<br>
<br>
<br>
///<br>
<br>
<br>
/// The value associated with the given key may be a null value as appropriate for the data format.<br>
<br>
<br>
///<br>
<br>
<br>
/// - parameter key: The key to search for.<br>
<br>
<br>
/// - returns: Whether the `Decoder` has an entry for the given key.<br>
<br>
open<br>
func contains(_ key: Key) -> Bool<br>
<br>
<br>
<br>
/// Decodes a value of the given type for the given key.<br>
<br>
<br>
///<br>
<br>
<br>
/// A default implementation is given for these types which calls into the abstract `decodeIfPresent` implementations below.<br>
<br>
<br>
///<br>
<br>
<br>
/// - parameter type: The type of value to decode.<br>
<br>
<br>
/// - parameter key: The key that the decoded value is associated with.<br>
<br>
<br>
/// - returns: A value of the requested type, if present for the given key and convertible to the requested type.<br>
<br>
<br>
/// - throws: `CocoaError.coderTypeMismatch` if the encountered encoded value is not convertible to the requested type.<br>
<br>
<br>
/// - throws: `CocoaError.coderValueNotFound` if `self` does not have an entry for the given key or if the value is null.<br>
<br>
open<br>
func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool<br>
<br>
open<br>
func decode(_ type: Int.Type, forKey key: Key) throws -> Int<br>
<br>
open<br>
func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8<br>
<br>
open<br>
func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16<br>
<br>
open<br>
func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32<br>
<br>
open<br>
func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64<br>
<br>
open<br>
func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt<br>
<br>
open<br>
func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8<br>
<br>
open<br>
func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16<br>
<br>
open<br>
func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32<br>
<br>
open<br>
func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64<br>
<br>
open<br>
func decode(_ type: Float.Type, forKey key: Key) throws -> Float<br>
<br>
open<br>
func decode(_ type: Double.Type, forKey key: Key) throws -> Double<br>
<br>
open<br>
func decode(_ type: String.Type, forKey key: Key) throws -> String<br>
<br>
open<br>
func decode(_ type: Data.Type, forKey key: Key) throws -> Data<br>
<br>
open<br>
func decode<Value : Codable>(_ type: Value.Type, forKey key: Key) throws -> Value<br>
<br>
<br>
<br>
/// Decodes a value of the given type for the given key, if present.<br>
<br>
<br>
///<br>
<br>
<br>
/// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be disambiguated with a `contains(_:)` call.<br>
<br>
<br>
///<br>
<br>
<br>
/// - parameter type: The type of value to decode.<br>
<br>
<br>
/// - parameter key: The key that the decoded value is associated with.<br>
<br>
<br>
/// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value.<br>
<br>
<br>
/// - throws: `CocoaError.coderTypeMismatch` if the encountered encoded value is not convertible to the requested type.<br>
<br>
open<br>
func decodeIfPresent(_ type: Bool.Type, forKey key: Key) throws -> Bool?<br>
<br>
open<br>
func decodeIfPresent(_ type: Int.Type, forKey key: Key) throws -> Int?<br>
<br>
open<br>
func decodeIfPresent(_ type: Int8.Type, forKey key: Key) throws -> Int8?<br>
<br>
open<br>
func decodeIfPresent(_ type: Int16.Type, forKey key: Key) throws -> Int16?<br>
<br>
open<br>
func decodeIfPresent(_ type: Int32.Type, forKey key: Key) throws -> Int32?<br>
<br>
open<br>
func decodeIfPresent(_ type: Int64.Type, forKey key: Key) throws -> Int64?<br>
<br>
open<br>
func decodeIfPresent(_ type: UInt.Type, forKey key: Key) throws -> UInt?<br>
<br>
open<br>
func decodeIfPresent(_ type: UInt8.Type, forKey key: Key) throws -> UInt8?<br>
<br>
open<br>
func decodeIfPresent(_ type: UInt16.Type, forKey key: Key) throws -> UInt16?<br>
<br>
open<br>
func decodeIfPresent(_ type: UInt32.Type, forKey key: Key) throws -> UInt32?<br>
<br>
open<br>
func decodeIfPresent(_ type: UInt64.Type, forKey key: Key) throws -> UInt64?<br>
<br>
open<br>
func decodeIfPresent(_ type: Float.Type, forKey key: Key) throws -> Float?<br>
<br>
open<br>
func decodeIfPresent(_ type: Double.Type, forKey key: Key) throws -> Double?<br>
<br>
open<br>
func decodeIfPresent(_ type: String.Type, forKey key: Key) throws -> String?<br>
<br>
open<br>
func decodeIfPresent(_ type: Data.Type, forKey key: Key) throws -> Data?<br>
<br>
open<br>
func decodeIfPresent<Value : Codable>(_ type: Value.Type, forKey key: Key) throws -> Value?<br>
<br>
<br>
<br>
/// The path of coding keys taken to get to this point in decoding.<br>
<br>
open<br>
var codingKeyContext: [CodingKey]<br>
}<br>
These encode(_:forKey:) and decode(_:forKey:) overloads give strong, static type guarantees about what is encodable (preventing accidental attempts to encode an invalid type), and provide a list of primitive types which are common to all encoders and decoders that users can rely on.<br>
<br>
Coming in Swift 4 is the ability to express that "a collection of things which are Codable is Codable" (conditional conformance), allowing collections which we extend (Array, Dictionary, etc.) to fall into these overloads as well.<br>
<br>
Encoding Container Types<br>
<br>
For some types, the container into which they encode has meaning. Especially when coding for a specific output format (e.g. when communicating with a JSON API), a type may wish to explicitly encode as an array or a dictionary:<br>
<br>
// Continuing from before<br>
public protocol Encoder {<br>
<br>
<br>
/// Populates `self` with an encoding container of the given type and returns it, keyed by the given key type.<br>
<br>
<br>
///<br>
<br>
<br>
/// A default implementation of `Encoder.container(keyedBy:)` calls this method with a container type of `.default`.<br>
<br>
<br>
///<br>
<br>
<br>
/// - parameter keyType: The key type to use for the container.<br>
<br>
<br>
/// - parameter containerType: The container type to create.<br>
<br>
<br>
/// - returns: A new keyed encoding container.<br>
<br>
<br>
/// - precondition: May not be called after a previous `self.container(keyedBy:)` call of a different `EncodingContainerType`.<br>
<br>
<br>
/// - precondition: May not be called after a value has been encoded through a prior `self.singleValueContainer()` call.<br>
<br>
<br>
func container<Key : CodingKey>(keyedBy keyType: Key.Type, type containerType: EncodingContainerType) -> KeyedEncodingContainer<Key><br>
}<br>
<br>
<br>
<br>
/// An `EncodingContainerType` specifies the type of container an `Encoder` should use to store values.<br>
public enum EncodingContainerType {<br>
<br>
<br>
/// The `Encoder`'s preferred container type; equivalent to either `.array` or `.dictionary` as appropriate for the encoder.<br>
<br>
<br>
case `default<br>
`<br>
<br>
<br>
/// Explicitly requests the use of an array to store encoded values.<br>
<br>
<br>
case<br>
array<br>
<br>
<br>
/// Explicitly requests the use of a dictionary to store encoded values.<br>
<br>
<br>
case<br>
dictionary<br>
<br>
}<br>
Single Value Containers<br>
<br>
For other types, an array or dictionary container may not even make sense (e.g. values which are RawRepresentable as a single primitive value). Those types may encode and decode directly as a single value, instead of requesting a keyed container:<br>
<br>
/// A `SingleValueEncodingContainer` is a container which can support the storage and direct encoding of a single non-keyed value.<br>
public protocol SingleValueEncodingContainer {<br>
<br>
<br>
/// Encodes a single value of the given type.<br>
<br>
<br>
///<br>
<br>
<br>
/// - parameter value: The value to encode.<br>
<br>
<br>
/// - throws: `CocoaError.coderInvalidValue` if the given value is invalid in the current context for this format.<br>
<br>
<br>
/// - precondition: May not be called after a previous `self.encode(_:)` call.<br>
<br>
<br>
func encode(_ value: Bool) throws<br>
<br>
<br>
func encode(_ value: Int) throws<br>
<br>
<br>
func encode(_ value: Int8) throws<br>
<br>
<br>
func encode(_ value: Int16) throws<br>
<br>
<br>
func encode(_ value: Int32) throws<br>
<br>
<br>
func encode(_ value: Int64) throws<br>
<br>
<br>
func encode(_ value: UInt) throws<br>
<br>
<br>
func encode(_ value: UInt8) throws<br>
<br>
<br>
func encode(_ value: UInt16) throws<br>
<br>
<br>
func encode(_ value: UInt32) throws<br>
<br>
<br>
func encode(_ value: UInt64) throws<br>
<br>
<br>
func encode(_ value: Float) throws<br>
<br>
<br>
func encode(_ value: Double) throws<br>
<br>
<br>
func encode(_ value: String) throws<br>
<br>
<br>
func encode(_ value: Data) throws<br>
}<br>
<br>
<br>
<br>
/// A `SingleValueDecodingContainer` is a container which can support the storage and direct decoding of a single non-keyed value.<br>
public protocol SingleValueDecodingContainer {<br>
<br>
<br>
/// Decodes a single value of the given type.<br>
<br>
<br>
///<br>
<br>
<br>
/// - parameter type: The type to decode as.<br>
<br>
<br>
/// - returns: A value of the requested type.<br>
<br>
<br>
/// - throws: `CocoaError.coderTypeMismatch` if the encountered encoded value cannot be converted to the requested type.<br>
<br>
<br>
func decode(_ type: Bool.Type) throws -> Bool<br>
<br>
<br>
func decode(_ type: Int.Type) throws -> Int<br>
<br>
<br>
func decode(_ type: Int8.Type) throws -> Int8<br>
<br>
<br>
func decode(_ type: Int16.Type) throws -> Int16<br>
<br>
<br>
func decode(_ type: Int32.Type) throws -> Int32<br>
<br>
<br>
func decode(_ type: Int64.Type) throws -> Int64<br>
<br>
<br>
func decode(_ type: UInt.Type) throws -> UInt<br>
<br>
<br>
func decode(_ type: UInt8.Type) throws -> UInt8<br>
<br>
<br>
func decode(_ type: UInt16.Type) throws -> UInt16<br>
<br>
<br>
func decode(_ type: UInt32.Type) throws -> UInt32<br>
<br>
<br>
func decode(_ type: UInt64.Type) throws -> UInt64<br>
<br>
<br>
func decode(_ type: Float.Type) throws -> Float<br>
<br>
<br>
func decode(_ type: Double.Type) throws -> Double<br>
<br>
<br>
func decode(_ type: String.Type) throws -> String<br>
<br>
<br>
func decode(_ type: Data.Type) throws -> Data<br>
}<br>
<br>
<br>
<br>
// Continuing example from before; below is automatically generated by the compiler if no customization is needed.<br>
public enum Animal : Int, Codable {<br>
<br>
<br>
public func encode(to encoder: Encoder) throws {<br>
<br>
<br>
// Encode as a single value; no keys.<br>
<br>
<br>
try encoder.singleValueContainer.encode(self.rawValue)<br>
<br>
<br>
}<br>
<br>
<br>
<br>
public init(from decoder: Decoder) throws {<br>
<br>
<br>
// Decodes as a single value; no keys.<br>
<br>
<br>
let intValue = try decoder.singleValueContainer().decode(Int.self)<br>
<br>
<br>
if let value = Self(rawValue: intValue) {<br>
<br>
<br>
self =<br>
value<br>
<br>
} else {<br>
<br>
<br>
throw CocoaError.error(.coderReadCorrupt)<br>
<br>
<br>
}<br>
<br>
<br>
}<br>
}<br>
In the example given above, since Animal uses a single value container, [.chicken, .dog, .cow, .turkey, .dog, .chicken, .cow, .turkey, .dog]would encode directly as [1, 2, 4, 3, 2, 1, 4, 3, 2].<br>
<br>
Nesting<br>
<br>
In practice, some types may also need to control how data is nested within their container, or potentially nest other containers within their container. Keyed containers allow this by returning nested containers of differing key types:<br>
<br>
// Continuing from before<br>
<br>
open<br>
class KeyedEncodingContainer<Key : CodingKey> {<br>
<br>
<br>
/// Stores an encoding container for the given key and returns it.<br>
<br>
<br>
///<br>
<br>
<br>
/// - parameter keyType: The key type to use for the container.<br>
<br>
<br>
/// - parameter containerType: The container type to create.<br>
<br>
<br>
/// - parameter key: The key to encode the container for.<br>
<br>
<br>
/// - returns: A new keyed encoding container.<br>
<br>
open<br>
func nestedContainer<NestedKey : CodingKey>(keyedBy keyType: NestedKey.Type, type containerType: EncodingContainerType, forKey key: Key) -> KeyedEncodingContainer<NestedKey><br>
}<br>
<br>
<br>
open<br>
class KeyedDecodingContainer<Key : CodingKey> {<br>
<br>
<br>
/// Returns the data stored for the given key as represented in a container keyed by the given key type.<br>
<br>
<br>
///<br>
<br>
<br>
/// - parameter type: The key type to use for the container.<br>
<br>
<br>
/// - parameter key: The key that the nested container is associated with.<br>
<br>
<br>
/// - returns: A keyed decoding container view into `self`.<br>
<br>
<br>
/// - throws: `CocoaError.coderTypeMismatch` if the encountered stored value is not a container.<br>
<br>
open<br>
func nestedContainer<NestedKey : CodingKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey><br>
}<br>
This can be common when coding against specific external data representations:<br>
<br>
// User type for interfacing with a specific JSON API. JSON API expects encoding as {"id": ..., "properties": {"name": ..., "timestamp": ...}}. Swift type differs from encoded type, and encoding needs to match a spec:<br>
struct Record : Codable {<br>
<br>
<br>
// We care only about these values from the JSON payload<br>
<br>
<br>
let id: Int<br>
<br>
<br>
let name: String<br>
<br>
<br>
let timestamp: Double<br>
<br>
<br>
<br>
// ...<br>
<br>
<br>
<br>
private enum Keys : CodingKey {<br>
<br>
<br>
case<br>
id<br>
<br>
case<br>
properties<br>
<br>
}<br>
<br>
<br>
<br>
private enum PropertiesKeys : CodingKey {<br>
<br>
<br>
case<br>
name<br>
<br>
case<br>
timestamp<br>
<br>
}<br>
<br>
<br>
<br>
public func encode(to encoder: Encoder) throws {<br>
<br>
<br>
let container = encoder.container(keyedBy: Keys.self, type: .dictionary)<br>
<br>
<br>
try container.encode(id, forKey: .id)<br>
<br>
<br>
<br>
// Set a dictionary for the "properties" key<br>
<br>
<br>
let nested = container.nestedContainer(keyedBy: PropertiesKeys.self, type: .dictionary, forKey: .properties)<br>
<br>
<br>
try nested.encode(name, forKey: .name)<br>
<br>
<br>
try nested.encode(timestamp, forKey: .timestamp)<br>
<br>
<br>
}<br>
<br>
<br>
<br>
public init(from decoder: Decoder) throws {<br>
<br>
<br>
let container = try decoder.container(keyedBy: Keys.self)<br>
<br>
id<br>
= try container.decode(Int.self, forKey: .id)<br>
<br>
<br>
<br>
let nested = try container.nestedContainer(keyedBy: PropertiesKeys.self, forKey: .properties)<br>
<br>
name<br>
= try nested.decode(String.self, forKey: .name)<br>
<br>
timestamp<br>
= try nested.decode(Double.self, forKey: .timestamp)<br>
<br>
<br>
}<br>
}<br>
Inheritance<br>
<br>
Inheritance in this system is supported much like it is with NSCoding — on encoding, objects which inherit from a type that is Codable encode super using their encoder, and pass a decoder to super.init(from:) on decode. With the existing NSCoding API, this is most often done like so, by convention:<br>
<br>
- (void)encodeWithCoder:(NSCoder *)encoder {<br>
<br>
<br>
[super encodeWithCoder:encoder];<br>
<br>
<br>
// ... encode properties<br>
}<br>
<br>
<br>
<br>
- (instancetype)initWithCoder:(NSCoder *)decoder {<br>
<br>
<br>
if ((self = [super initWithCoder:decoder])) {<br>
<br>
<br>
// ... decode properties<br>
<br>
<br>
}<br>
<br>
<br>
<br>
return self;<br>
}<br>
In practice, this approach means that the properties of self and the properties of super get encoded into the same container: if self encodes values for keys "a", "b", and "c", and super encodes "d", "e", and "f", the resulting object is archived as {"a": ..., "b": ..., "c": ..., "d": ..., "e": ..., "f": ...}. This approach has two drawbacks:<br>
<br>
        • Things which self encodes may overwrite super's (or vice versa, depending on when -[super encodeWithCoder:] is called<br>
        • self and super may not encode into different container types (e.g. self in a sequential fashion, and super in a keyed fashion)<br>
The second point is not an issue for NSKeyedArchiver, since all values encode with keys (sequentially coded elements get autogenerated keys). This proposed API, however, allows for self and super to explicitly request conflicting containers (.arrayand .dictionary, which may not be mixed, depending on the data format).<br>
<br>
To remedy both of these points, we adopt a new convention for inheritance-based coding — encoding super as a sub-object of self:<br>
<br>
public class MyCodable : SomethingCodable {<br>
<br>
<br>
public func encode(to encoder: Encoder) throws {<br>
<br>
<br>
let container = encoder.container(keyedBy: CodingKeys.self)<br>
<br>
<br>
// ... encode some properties<br>
<br>
<br>
<br>
// superEncoder() gives `super` a nested container to encode into (for<br>
<br>
<br>
// a predefined key).<br>
<br>
<br>
try super.encode(to: container.superEncoder())<br>
<br>
<br>
}<br>
<br>
<br>
<br>
public init(from decoder: Decoder) throws {<br>
<br>
<br>
let container = try decoder.container(keyedBy: CodingKeys.self)<br>
<br>
<br>
// ... decode some properties<br>
<br>
<br>
<br>
// Allow `super` to decode from the nested container.<br>
<br>
<br>
try super.init(from: container.superDecoder())<br>
<br>
<br>
}<br>
}<br>
If a shared container is desired, it is still possible to call super.encode(to: encoder) and super.init(from: decoder), but we recommend the safer containerized option.<br>
<br>
superEncoder() and superDecoder() are provided on KeyedEncodingContainer and KeyedDecodingContainer to provide handles to containers for super to use. While users may specify a custom key to encode super with, the default behavior is to use a key with a stringValue of "super" and an intValue of 0:<br>
<br>
// Continuing from before<br>
<br>
open<br>
class KeyedEncodingContainer<Key : CodingKey> {<br>
<br>
<br>
/// Stores a new nested container for the default `super` key and returns a new `Encoder` instance for encoding `super` into that container.<br>
<br>
<br>
///<br>
<br>
<br>
/// Equivalent to calling `superEncoder(forKey:)` with `Key(stringValue: "super", intValue: 0)`.<br>
<br>
<br>
///<br>
<br>
<br>
/// - returns: A new `Encoder` to pass to `super.encode(to:)`.<br>
<br>
open<br>
func superEncoder() -> Encoder<br>
<br>
<br>
<br>
/// Stores a new nested container for the given key and returns a new `Encoder` instance for encoding `super` into that container.<br>
<br>
<br>
///<br>
<br>
<br>
/// - parameter key: The key to encode `super` for.<br>
<br>
<br>
/// - returns: A new `Encoder` to pass to `super.encode(to:)`.<br>
<br>
<br>
/// - precondition: The key must have a `stringValue` or `intValue` appropriate for the encoding container type.<br>
<br>
open<br>
func superEncoder(forKey key: Key) -> Encoder<br>
}<br>
<br>
<br>
open<br>
class KeyedDecodingContainer<Key : CodingKey> {<br>
<br>
<br>
/// Returns a `Decoder` instance for decoding `super` from the container associated with the default `super` key.<br>
<br>
<br>
///<br>
<br>
<br>
/// Equivalent to calling `superDecoder(forKey:)` with `Key(stringValue: "super", intValue: 0)`.<br>
<br>
<br>
///<br>
<br>
<br>
/// - returns: A new `Decoder` to pass to `super.init(from:)`.<br>
<br>
<br>
/// - throws: `CocoaError.coderValueNotFound` if `self` does not have an entry for the default `super` key, or if the stored value is null.<br>
<br>
open<br>
func superDecoder() throws -> Decoder<br>
<br>
<br>
<br>
/// Returns a `Decoder` instance for decoding `super` from the container associated with the given key.<br>
<br>
<br>
///<br>
<br>
<br>
/// - parameter key: The key to decode `super` for.<br>
<br>
<br>
/// - returns: A new `Decoder` to pass to `super.init(from:)`.<br>
<br>
<br>
/// - throws: `CocoaError.coderValueNotFound` if `self` does not have an entry for the given key, or if the stored value is null.<br>
<br>
open<br>
func superDecoder(forKey key: Key) throws -> Decoder<br>
}<br>
Primitive Codable Conformance<br>
<br>
The encoding container types offer overloads for working with and processing the API's primitive types (String, Int, Double, etc.). However, for ease of implementation (both in this API and others), it can be helpful for these types to conform to Codable themselves. Thus, along with these overloads, we will offer Codableconformance on these types:<br>
<br>
extension Bool : Codable {<br>
<br>
<br>
public init(from decoder: Decoder) throws {<br>
<br>
<br>
self = try decoder.singleValueContainer().decode(Bool.self)<br>
<br>
<br>
}<br>
<br>
<br>
<br>
public func encode(to encoder: Encoder) throws {<br>
<br>
<br>
try encoder.singleValueContainer().encode( self)<br>
<br>
<br>
}<br>
}<br>
<br>
<br>
<br>
// Repeat for others...<br>
This conformance allows one to write functions which accept Codable types without needing specific overloads for the fifteen primitive types as well. This also simplifies conditional conformance (e.g. expressing "extension Array : Codable where Element : Codable") by removing the need for additional explicit conformances for these types.<br>
<br>
Since Swift's function overload rules prefer more specific functions over generic functions, the specific overloads are chosen where possible (e.g. encode("Hello, world!", forKey: .greeting) will choose encode(_: String, forKey: Key) over encode<T : Codable>(_: T, forKey: Key)). This maintains performance over dispatching through the Codable existential, while allowing for the flexibility of fewer overloads where applicable.<br>
<br>
Additional Extensions<br>
<br>
Along with the primitive Codable conformance above, extensions on CodableRawRepresentable types whose RawValue is a primitive types will provide default implementations for encoding and decoding:<br>
<br>
public extension RawRepresentable where RawValue == Bool, Self : Codable {<br>
<br>
<br>
public init(from decoder: Decoder) throws {<br>
<br>
<br>
let decoded = try decoder.singleValueContainer().decode(RawValue.self)<br>
<br>
<br>
guard let value = Self(rawValue: decoded) else {<br>
<br>
<br>
throw CocoaError.error(.coderReadCorrupt)<br>
<br>
<br>
}<br>
<br>
<br>
<br>
self =<br>
value<br>
<br>
}<br>
<br>
<br>
<br>
public func encode(to encoder: Encoder) throws {<br>
<br>
<br>
try encoder.singleValueContainer().encode(self.rawValue)<br>
<br>
<br>
}<br>
}<br>
<br>
<br>
<br>
// Repeat for others...<br>
This allows for trivial Codable conformance of enum types (and manual RawRepresentable implementations) with primitive backing.<br>
<br>
Source compatibility<br>
This proposal is additive — existing code will not have to change due to this API addition. This implementation can be made available in both Swift 4 and the Swift 3 compatibility mode.<br>
<br>
Effect on ABI stability<br>
The addition of this API will not be an ABI-breaking change. However, this will add limitations for changes in future versions of Swift, as parts of the API will have to remain unchanged between versions of Swift (barring some additions, discussed below).<br>
<br>
Effect on API resilience<br>
Much like new API added to the standard library, once added, many changes to this API will be ABI- and source-breaking changes. In particular, changes which change the types or names of methods or arguments, add required methods on protocols or classes, or remove supplied default implementations will break client behavior.<br>
<br>
The following protocols and classes may not have methods added to them without providing default implementations:<br>
<br>
        • Codable<br>
        • CodingKey<br>
        • Encoder<br>
        • SingleValueEncodingContainer<br>
        • KeyedEncodingContainer<br>
        • Decoder<br>
        • SingleValueDecodingContainer<br>
        • KeyedDecodingContainer<br>
The following classes may not remove existing default implementations:<br>
<br>
        • KeyedEncodingContainer<br>
        • KeyedDecodingContainer<br>
Various extensions to Swift primitive types (Bool, Int, Double, etc.) and to RawRepresentable types (where RawValue == Bool, == Int, == Double, etc.) may also not be removed.<br>
<br>
In general, changes to the proposed types will be restricted as described in the library evolution document in the Swift repository.<br>
<br>
_______________________________________________<br>
swift-evolution mailing list<br>
swift-evolution@swift.org<br>
<a href="https://lists.swift.org/mailman/listinfo/swift-evolution" style="color:#999">https://lists.swift.org/mailman/listinfo/swift-evolution</a></p>
</blockquote></blockquote></div>
<div style="white-space:normal">
</div>
</div>
</body>
</html>