Skip to content

Decoding subclasses #459

@mdiep

Description

@mdiep

I'm trying to convert some code to use Argo, and I'm getting stuck where the existing code uses subclasses. I can't get type inference to pass.

If anyone knows how to get this to work, I'd love some help.

Error Messages

error: cannot convert value of type 'Decoded<_>' to specified type 'Decoded<Child>'
    let child: Decoded<Child> = json <| "child"
                                ~~~~~^~~~~~~~~~
error: cannot convert value of type 'Decoded<[_]?>' (aka 'Decoded<Optional<Array<_>>>') to specified type 'Decoded<[Child]?>' (aka 'Decoded<Optional<Array<Child>>>')
    let children: Decoded<[Child]?> = json <||? "children"
                                      ~~~~~^~~~~~~~~~~~~~~

Models

class Parent: Decodable {
  let title: String

  init(title: String) {
    self.title = title
  }

  typealias DecodedType = Parent
  static func decode(_ json: JSON) -> Decoded<Parent> {
    return curry(Parent.init)
      <^> json <| "title"
  }
}

class Child: Parent {
  let subtitle: String

  init(title: String, subtitle: String) {
    self.subtitle = subtitle
    super.init(title: title)
  }

  typealias DecodedType = Child
  static func decode(_ json: JSON) -> Decoded<Child> {
    return curry(Child.init)
      <^> json <| "title"
      <*> json <| "subtitle"
  }
}

final class Consumer: Decodable {
  let child: Child
  let children: [Child]?

  init(child: Child, children: [Child]?) {
    self.child = child
    self.children = children
  }

  static func decode(_ json: JSON) -> Decoded<Consumer> {
    // Changing these from Child to Parent makes it work
    let child: Decoded<Child> = json <| "child"
    let children: Decoded<[Child]?> = json <||? "children"
    return curry(self.init)
      <^> child
      <*> children
  }
}

Argo Version

Argo 4.1.2
Xcode 8.3.2

Dependency Manager

Carthage

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions