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)

6
  • What's the actual problem? Commented Mar 15, 2017 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. Commented Mar 16, 2017 at 8:52
  • Why is that a problem? This is standard OO programming. Look up inheritance and overriding Commented Mar 16, 2017 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. Commented Mar 16, 2017 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. Commented Mar 16, 2017 at 10:29

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.