[swift-evolution] [Pitch] DateComponents{Encoding/Decoding}Strategy in JSON{Encoder/Decoder}

Pitiphong Phongpattranont pitiphong.p at me.com
Sun Sep 3 02:54:27 CDT 2017


Hi folks, I have an idea on improving the JSON{Encoder/Decoder} to pitch.

Since JSON doesn’t have a native representation for `DateComponents` like it doesn’t have for `Date` too so that there’re many ways to represent it in JSON, for example ISO 8601, UNIX timestamp, etc. for Date. There are also a few ways to represent `DateComponents` too, for example ISO 8601 (https://en.wikipedia.org/wiki/ISO_8601) also describes how to represent some of the valid date components (e.g. "2017-09-03”).  Unlike what JSON{Encoder/Decoder} does to represent `Date` value with several strategy but there is no support like that for `DateComponents`.

The current implementation DateComponents is to encode/decode with KeyedContainer and cannot provide a custom or ISO 8601 compatible implementation. So I think JSON{Encoder/Decoder} should have a strategy for encoding/decoding `DateComponents` just like for Date

Here’s an initial `DateComponentsStrategy` strategy that I want JSON{Encoder/Decoder}  I can think of now, any suggestion is welcomed.

```swift
  /// The strategy to use for encoding `DateComponents` values.
  public enum DateComponentsStrategy {
    /// Defer to `Date` for choosing an encoding. This is the default strategy.
    case deferredToDateComponents
    
    /// Encode the `Date` as an ISO-8601-formatted string (in RFC 3339 format).
    case iso8601
    
    /// Encode the `Date` as a custom value encoded by the given closure.
    ///
    /// If the closure fails to encode a value into the given encoder, the encoder will encode an empty automatic container in its place.
    case custom((DateComponents, Encoder) throws -> Void)
  }
```

What do you guys think about this pitch?


Pitiphong Phongpattranont


More information about the swift-evolution mailing list