I get back two dictionaries, I need to parse through them and put in an array two objects. I think I did a very poor job and I have a feeling there is a better way to make the code more compact and generic.

I think there is definitely a way to combine these two loops. Please advise on any better way to accomplish this:

var cases = [[String: AnyObject]]()
var statuses = [[String: AnyObject]]()
var retVal = [AnyObject]()
var dict = [String: AnyObject]()    

if jsonReturnValue != nil {
        let (hasError, errorMessage) =  ErrorHandler.hasError(jsonReturnValue)

        if hasError {
            //TODO Display a proper error to the user
            )
            print("Error Message: \(errorMessage)")
        } else {
            for value in jsonReturnValue {
                for (var i = 0; i < value.1.count; i++) {

                    if let dataDict = value.1 as? [String: AnyObject] {

                        let status = dataDict["status"]
                        let case = dataDict["case"]

                        // I think I can combine the two loops below but not sure how.

                        if let val = status as? [AnyObject] {
                            if let items = val[i] as? [String: AnyObject] {

                                for item in items {
                                    dict[item.0] = item.1
                                }
                            }
                            cases.append(dict)
                        }

                        dict.removeAll()

                        if let val = case as? [AnyObject] {
                            if let items = val[i] as? [String: AnyObject] {

                                for item in items {
                                    dict[item.0] = item.1
                                }
                            }
                            statuses.append(dict)
                        }
                    }
                }
            }
        }
    }
    retVal.removeAll()
    retVal.append(cases)
    retVal.append(statuses)
    return retVal
 }
  • Some more information would be useful. What type has jsonReturnValue and what does it (typically) contain? Where does ErrorHandler.hasError() come from? – Martin R Nov 19 '15 at 5:52
  • Only post compiling code to Code Review: Define jsonReturnValue, ErrorHandler, the enclosing function and use something other than case for your variable since case is a keyword and can't be used. – Kametrixom Nov 21 '15 at 14:34

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Browse other questions tagged or ask your own question.