0

I am working on an app that parses XML responses from a web service. This web service will return several instances of an object of many different types using object stacking. I just want to take these objects and populate them into an array. Right now I have a switch that is repeating several different lines of similar code based on "objectStack.last" type. This is what it looks like right now in the parserDidEndElement function of the XML parser:

    switch(objectStack.last){
    case _ as apple:
        apples.removeAll()
        for apple in objectStack as! [apple]{
            apples.append(apple.name.value)
        objectType = "apple"
        }
    case _ as orage:
        oranges.removeAll()
        for orange in objectStack as! [orange]{
            oranges.append(orange.name.value)
        }
        objectType = "orange"
    case _ as bananas:
        bananas.removeAll()
        for banana in objectStack as! [banana]{
            bananas.append(banana.name.value)
        }
        objectType = "banana"
    case default:
        break

The problem is that the webservice will be returning a large number of different types, and I would rather not have to build a switch case for each. For the purposes of this discussion, let's say I have created an empty array for each type just by adding a "s" to the type name (ie apples, oranges and bananas). Is there a way for me to manipulate the arrays using a variable? Something like this:

   objectStack.last + "s".removeAll()
   for objectStack.last in objectStack.last + "s" as! [objectStack.last]{
      objectStack.last + "s".append(objectStack.last.name.value)
      objectType = objectStack.last
   }

Obviously this second code block is not valid code, I'm just hoping it helps to illustrate what I am trying to accomplish.

Thanks in advance for your help!

2
  • Put em in a dictionary is the most obvious answer Commented Feb 11, 2017 at 6:29
  • @DavidBerry what would that look like? Commented Feb 11, 2017 at 6:40

1 Answer 1

0

I ended up using inheritance to fix my issue. Although I have objects of many types, I created a "baseObject" class that contains the fields I needed for this to be successful. I was then able to use the following:

for obj in objectStack{
    let obj2 = obj as! baseObject
    fieldArrays[objectType]!.append(obj2.name.value)
}

I also used the solution here to use a dictionary to populate the correct array using the "didSet" event on the dictionary.

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.