Anviking / Decodable

[Probably deprecated] Swift 2/3 JSON unmarshalling done (more) right
MIT License
1.04k stars 73 forks source link

How can I decode a class hierarchy if I cannot override decode (static method) #139

Closed Ricardo1980 closed 7 years ago

Ricardo1980 commented 7 years ago

Hello,

Let's say I have a base class, A, with a field called type (just a string). Then I have class B (subclass of A) with several fields more. Similar for class C.

If I implement decode (a static method) in A to check type and then depending on that, I try to decode it using B or C decode method, and return an instance of B or C rather than A. But I receive that I cannot override a static method, that's my problem.

A could be an abstract class (although seems to me that concept does not exist in Swift). Any suggestion? How should I do this? I know I could achieve something similar using protocols, but I would like to know if I can use decodable when subclassing is involved.

Thanks in advance.

voidref commented 7 years ago

Decodable has been designed around the strategy of using Swift Structs, which do not support a hierarchy.

You could use composition, that is, have your classes use structs to hold their data and take the json in their constructors to populate their particular structs up the hierarchy.

class base {
    struct baseStruct: Decodable {
    }
    var baseData:baseStruct
   init(json) {
      baseData => json
   }
}

class derived : base {
  struct derivedStruct: Decodable {
  }

  var derivedData: derivedStruct

  init(json) {
    derivedData => json
    super.init(json)
  }
}

That sort of thing (really bad pseudo code).

HTH!

Ricardo1980 commented 7 years ago

Thanks mate!