thoughtbot/Argo

Decoding subclasses

Open

#459 opened on May 11, 2017

View on GitHub
 (15 comments) (0 reactions) (0 assignees)Swift (3,455 stars) (214 forks)batch import
help wantedquestion

Description

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

Contributor guide