2

I have a base parent object like this:

class A: Mappable {
    var x: String!
    ...
}

And two children of it:

class Child1: A {
    var y: Int!
    ...
}

class Child2: A {
    var z: String?
}

All this is good and dandy, but what happens when I have an object that represents an array of objects that inherit from A such as:

class Wrapper: Mappable {
    var objcs: [A]? // A will always be either Child1 or Child2, never A directly
}

How do I manage this situation? (little detail, I need to be able to use Wrapper from Obj-c as well, didn't add the annotations and NSObject inheritance to avoid being verbose)

la_f0ka
  • 1,773
  • 3
  • 23
  • 44
  • What's the actual problem? – JeremyP Mar 15 '17 at 15:35
  • the problem is that the library will not recognise the objects in Wrapper as possibly Child1 or ChildB types, and will instead cast them all as A. – la_f0ka Mar 16 '17 at 08:52
  • Why is that a problem? This is standard OO programming. Look up inheritance and overriding – JeremyP Mar 16 '17 at 10:12
  • I dont think you understood my question JeremyP. My problem wasn't a lack of knowledge on OO programming, but a lack of knowledge on where to hook to properly cast my objects in ObjectMapper. I added the answer for anyone who might be interested. – la_f0ka Mar 16 '17 at 10:15
  • If you have to look inside an object to find out what it is, that's a code smell. Your design probably needs to be looked at again. – JeremyP Mar 16 '17 at 10:29
  • I agree, but the models are mapped after an API over which I have no control – la_f0ka Mar 16 '17 at 10:36

1 Answers1

2

I managed to solve this issue, so I'm leaving this for posterity in case anyone runs across this issue:

I had to implement a custom TransformType (a protocol of the ObjectMapper library) that takes the list of [Any] and converts them independently to either Child1 or Child2 depending on the internal structure of Any

la_f0ka
  • 1,773
  • 3
  • 23
  • 44