<html><head><meta http-equiv="Content-Type" content="text/html charset=utf-8"></head><body style="word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space;" class=""><div class="">You’re right, my current implementation doesn’t win anything over what you’re written - &nbsp;in fact your technique is basically what I wrote at first.</div><div class=""><br class=""></div><div class="">I was trying to work towards encapsulating the behavior in the encoder/decoder so that the automatic init/encode methods could work, so I wanted to introduce my first (more manual) attempt and then say, here’s where I’d like to get with this.</div><div class=""><br class=""></div><div class="">-Wil</div><div class=""><br class=""></div><br class=""><div><blockquote type="cite" class=""><div class="">On Jul 11, 2017, at 10:16 AM, Itai Ferber &lt;<a href="mailto:iferber@apple.com" class="">iferber@apple.com</a>&gt; wrote:</div><br class="Apple-interchange-newline"><div class="">


<meta http-equiv="Content-Type" content="text/xhtml; charset=utf-8" class="">

<div class="">
<div style="font-family:sans-serif" class=""><div style="white-space:normal" class=""><p dir="auto" class="">Hi Wil,</p><p dir="auto" class="">Thanks for putting this together! My biggest thought on this is — what does this provide that you can’t already do yourself today?<br class="">
Since you have to go through the work to put together default values and override <code style="background-color:#F7F7F7; border-radius:3px; margin:0; padding:0 0.4em" bgcolor="#F7F7F7" class="">init(from:)</code> and <code style="background-color:#F7F7F7; border-radius:3px; margin:0; padding:0 0.4em" bgcolor="#F7F7F7" class="">encode(to:)</code> to use them, I’m wondering whether this saves you any work over doing something like the following:</p>

<pre style="background-color: rgb(247, 247, 247); border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; margin-left: 15px; margin-right: 15px; max-width: 90vw; overflow-x: auto; padding: 5px;" bgcolor="#F7F7F7" class=""><code style="background-color:#F7F7F7; border-radius:3px; margin:0; padding:0" bgcolor="#F7F7F7" class=""><span style="color: #008800; font-weight: bold" class="">struct</span> <span style="color: #BB0066; font-weight: bold" class="">Theme</span> {
    <span style="color: #008800; font-weight: bold" class="">private</span> <span style="color: #008800; font-weight: bold" class="">static</span> <span style="color: #008800; font-weight: bold" class="">let</span> <span style="color: #996633" class="">_defaultName</span> = <span style="background-color: #fff0f0" class="">""</span>
    <span style="color: #008800; font-weight: bold" class="">private</span> <span style="color: #008800; font-weight: bold" class="">static</span> <span style="color: #008800; font-weight: bold" class="">let</span> <span style="color: #996633" class="">_defaultStyles</span>: [<span style="color: #007020" class="">String</span>] = []

    <span style="color: #008800; font-weight: bold" class="">public</span> <span style="color: #008800; font-weight: bold" class="">let</span> <span style="color: #996633" class="">name</span>: <span style="color: #007020" class="">String</span>
    <span style="color: #008800; font-weight: bold" class="">public</span> <span style="color: #008800; font-weight: bold" class="">let</span> <span style="color: #996633" class="">styles</span>: [<span style="color: #007020" class="">String</span>]

    <span style="color: #008800; font-weight: bold" class="">private</span> <span style="color: #008800; font-weight: bold" class="">enum</span> <span style="color: #BB0066; font-weight: bold" class="">CodingKeys</span> : <span style="color: #007020" class="">String</span>, CodingKey {
        <span style="color: #008800; font-weight: bold" class="">case</span> name
        <span style="color: #008800; font-weight: bold" class="">case</span> styles
    }

    <span style="color: #008800; font-weight: bold" class="">public</span> <span style="color: #008800; font-weight: bold" class="">init</span>(from decoder: Decoder) throws {
        <span style="color: #008800; font-weight: bold" class="">let</span> <span style="color: #996633" class="">container</span> = try decoder.container(keyedBy: CodingKeys.<span style="color: #008800; font-weight: bold" class="">self</span>)
        name = try? decoder.decode(<span style="color: #007020" class="">String</span>.<span style="color: #008800; font-weight: bold" class="">self</span>, forKey: .name) ?? Theme._defaultName
        styles = try? decoder.decode([<span style="color: #007020" class="">String</span>.<span style="color: #008800; font-weight: bold" class="">self</span>], forKey: .styles) ?? Theme._defaultStyles
    }

    <span style="color: #008800; font-weight: bold" class="">public</span> <span style="color: #008800; font-weight: bold" class="">func</span> <span style="color: #0066BB; font-weight: bold" class="">encode</span>(to encoder: Encoder) throws {
        <span style="color: #008800; font-weight: bold" class="">var</span> <span style="color: #996633" class="">container</span> = encoder.container(keyedBy: CodingKeys.<span style="color: #008800; font-weight: bold" class="">self</span>)
        <span style="color: #008800; font-weight: bold" class="">if</span> (name <span style="color: #333333" class="">!=</span> Theme._defaultName) try container.encode(name, forKey: .name)
        <span style="color: #008800; font-weight: bold" class="">if</span> (styles <span style="color: #333333" class="">!=</span> Theme._defaultStyles) try container.encode(styles, forKey: .styles)
    }
}
</code></pre><p dir="auto" class="">This reads just as clearly to me as the <code style="background-color:#F7F7F7; border-radius:3px; margin:0; padding:0 0.4em" bgcolor="#F7F7F7" class="">defaults:</code> variation while having the added benefit of low complexity and stronger type safety (as there’s no <code style="background-color:#F7F7F7; border-radius:3px; margin:0; padding:0 0.4em" bgcolor="#F7F7F7" class="">as!</code>-casting down from <code style="background-color:#F7F7F7; border-radius:3px; margin:0; padding:0 0.4em" bgcolor="#F7F7F7" class="">Any</code>, which could fail).</p><p dir="auto" class="">Thoughts?</p><p dir="auto" class="">— Itai</p><p dir="auto" class="">On 10 Jul 2017, at 17:16, William Shipley via swift-evolution wrote:</p>

</div>
<div style="white-space:normal" class=""><blockquote style="border-left:2px solid #777; color:#777; margin:0 0 5px; padding-left:5px" class=""><p dir="auto" class="">Automatic substitution / removal of default values is very useful when reading or writing a file, respectively, and should be supported by the &lt;Codable&gt; family of protocols and objects:<br class="">
<br class="">
• When reading, swapping in a default value for missing or corrupted values makes it so hand-created or third-party-created files don’t have to write every single value to make a valid file, and allows slightly corrupted files to auto-repair (or get close, and let the user fix up any data that needs it after) rather than completely fail to load. (Repairing on read creates a virtuous cycle with user-created files, as the user will get _some_ feedback on her input even if she’s messed up, for example, the type of one of the properties.)<br class="">
<br class="">
• When writing, providing a default value allows the container to skip keys that don’t contain useful information. This can dramatically reduce file sizes, but I think its other advantages are bigger wins: just like having less source code makes a program easier to debug, having less “data code” makes files easier to work with in every way — they’re easier to see differences in, easier to determine corruption in, easier to edit by hand, and easier to learn from.<br class="">
<br class="">
<br class="">
My first pass attempt at adding defaults to Codable looks like this:<br class="">
<br class="">
<br class="">
public class ReferencePieceFromModel : Codable {<br class="">
<br class="">
    // MARK: properties<br class="">
    public let name: String = ""<br class="">
    public let styles: [String] = []<br class="">
<br class="">
<br class="">
    // MARK: &lt;Codable&gt;<br class="">
    public required init(from decoder: Decoder) throws {<br class="">
        let container = try decoder.container(keyedBy: CodingKeys.self)<br class="">
<br class="">
        self.name = container.decode(String.self, forKey: .name, defaults: type(of: self).defaultsByCodingKey)<br class="">
        self.styles = container.decode([String].self, forKey: .styles, defaults: type(of: self).defaultsByCodingKey)<br class="">
    }<br class="">
    public func encode(to encoder: Encoder) throws {<br class="">
        var container = encoder.container(keyedBy: CodingKeys.self)<br class="">
<br class="">
        try container.encode(name, forKey: .name, defaults: type(of: self).defaultsByCodingKey)<br class="">
        try container.encode(styles, forKey: .styles, defaults: type(of: self).defaultsByCodingKey)<br class="">
    }<br class="">
    private static let defaultsByCodingKey: [CodingKeys : Any] = [<br class="">
        .name : "",<br class="">
        .styles : [String]()<br class="">
    ]<br class="">
<br class="">
<br class="">
    // MARK: private<br class="">
    private enum CodingKeys : String, CodingKey {<br class="">
        case name<br class="">
        case styles<br class="">
    }<br class="">
}<br class="">
<br class="">
With just a couple additions to the Swift libraries:<br class="">
<br class="">
extension KeyedDecodingContainer where Key : Hashable {<br class="">
    func decode&lt;T&gt;(_ type: T.Type, forKey key: Key, defaults: [Key : Any]) -&gt; T where T : Decodable {<br class="">
        if let typedValueOptional = try? decodeIfPresent(T.self, forKey: key), let typedValue = typedValueOptional {<br class="">
            return typedValue<br class="">
        } else {<br class="">
            return defaults[key] as! T<br class="">
        }<br class="">
    }<br class="">
}<br class="">
<br class="">
extension KeyedEncodingContainer where Key : Hashable {<br class="">
    mutating func encode&lt;T&gt;(_ value: T, forKey key: Key, defaults: [Key : Any]) throws where T : Encodable &amp; Equatable {<br class="">
        if value != (defaults[key] as! T) {<br class="">
            try encode(value, forKey: key)<br class="">
        }<br class="">
    }<br class="">
<br class="">
    mutating func encode&lt;T&gt;(_ value: [T], forKey key: Key, defaults: [Key : Any]) throws where T : Encodable &amp; Equatable { // I AM SO SORRY THIS IS ALL I COULD FIGURE OUT TO MAKE [String] WORK!<br class="">
        if value != (defaults[key] as! [T]) {<br class="">
            try encode(value, forKey: key)<br class="">
        }<br class="">
    }<br class="">
}<br class="">
<br class="">
<br class="">
(Note the horrible hack on KeyedEncodingContainer where I had to special-case arrays of &lt;Equatable&gt;s, I guess because the compiler doesn’t know an array of &lt;Equatable&gt;s is Equatable itself?)<br class="">
<br class="">
<br class="">
Problems with this technique I’ve identified are:<br class="">
<br class="">
⑴ It doesn’t allow one to add defaults without manually writing the init(from:) and encode(to:), ugh.<br class="">
⑵ The programmer has to add 'type(of: self).defaultsByCodingKey’ to every call, ugh.<br class="">
<br class="">
Both of these could possibly be worked around if we could add an optional method to the &lt;Codable&gt; protocol, that would look something like:<br class="">
<br class="">
    public static func default&lt;Key&gt;(keyedBy type: Key.Type, key: Key) -&gt; Any? where Key : CodingKey<br class="">
<br class="">
(the above line isn’t tested and doubtlessly won’t work as typed and has tons of think-os.)<br class="">
<br class="">
This would get called by KeyedEncodingContainers and KeyedDecodingContainers only for keys that are Hashable (which I think is all keys, but you can stick un-keyed sub-things in Keyed containers and obviously those can’t have defaults just for them) and the container would be asked to do the comparison itself, with ‘==‘.<br class="">
<br class="">
Something I haven’t tried to address here is what to do if values are NOT &lt;Equatable&gt; — then of course ‘==‘ won’t work. One approach to this would be to provide a way for the static func above to return ‘Hey, I don’t have anything meaningful for you for this particular property, because it’s not Equatable.’ This could be as simple as returning ‘nil’, which would also be a decent way to say, “This property has no meaningful default” which is also needed.<br class="">
<br class="">
Alternatively, one could imagine adding TWO callbacks in the &lt;Codable&gt; for this kind of case, which are essentially *WAVES HANDS*:<br class="">
<br class="">
     public static func isThisValueTheDefault(_ value: Any, forKey key: Self.Key) throws -&gt; Any?<br class="">
     public static func defaultValue&lt;Key&gt;(keyedBy type: Key.Type, key: Key) -&gt; Any? where Key : CodingKey<br class="">
<br class="">
These might also need a 'keyedBy type: Key.Type’ parameter — to be honest I haven’t messed with different key spaces so I’m not sure how they work. Also I’m not the best at generics yet. (At this point I’m not even sure if protocols can contain ‘class’ functions, so maybe none of this would work.)<br class="">
<br class="">
Another advantage to the two-method approach (besides not requiring the values to be &lt; Equatable &gt;) is that it allows one to provide defaults for floating values, which can often be changed just by floating-point error by like 0.00000000001 and then end up registering false changes. In the isValueDefault(…) the programmer could implement a comparison with a ‘slop’ so if the encoder were about to write 0.000000000001 and the default were 0 nothing would be written.<br class="">
<br class="">
<br class="">
-Wil<br class="">
<br class="">
_______________________________________________<br class="">
swift-evolution mailing list<br class="">
<a href="mailto:swift-evolution@swift.org" class="">swift-evolution@swift.org</a><br class="">
<a href="https://lists.swift.org/mailman/listinfo/swift-evolution" style="color:#777" class="">https://lists.swift.org/mailman/listinfo/swift-evolution</a></p>
</blockquote></div>
<div style="white-space:normal" class="">
</div>
</div>
</div>

</div></blockquote></div><br class=""></body></html>