Skip to content

[Complex] Encode and decode using unkeyedContainer #95

@benrimmington

Description

@benrimmington

The encoding would change from {"x":0,"y":0} to [0,0] in JSON.

SE-0239 was originally pitched with CodingKeys, but in a discussion of the implementation, Tony Parker wrote:

This is one of those cases where I think we should just use two unkeyed values. ClosedRange is well defined and I don't think it's likely for it to grow the need for more keys. Same goes for the other Range types.

This would probably also make the encoded range types more parsable by other languages when encoded to JSON.

... I feel very strongly that we should prefer a compact representation for fundamental and mathematically-defined types like this.

Instead of the synthesized conformance, we could use the following:

extension Complex: Decodable where RealType: Decodable {
  public init(from decoder: Decoder) throws {
    var unkeyedContainer = try decoder.unkeyedContainer()
    let x = try unkeyedContainer.decode(RealType.self)
    let y = try unkeyedContainer.decode(RealType.self)
    self.init(x, y)
  }
}

extension Complex: Encodable where RealType: Encodable {
  public func encode(to encoder: Encoder) throws {
    var unkeyedContainer = encoder.unkeyedContainer()
    try unkeyedContainer.encode(x)
    try unkeyedContainer.encode(y)
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions