Search code examples
swiftnsarraynsdictionaryanyobject

How to identify the type of an object?


Here is my JSON response for a particular API.

Case 1

  ChallengeConfiguration =     {
            AnswerAttemptsAllowed = 0;
            ApplicantChallengeId = 872934636;
            ApplicantId = 30320480;
            CorrectAnswersNeeded = 0;

            MultiChoiceQuestion =         (
               {
    FullQuestionText = "From the following list, select one of your current or previous employers.";
    QuestionId = 35666244;
    SequenceNumber = 1;
                },
                {
    FullQuestionText = "What color is/was your 2010 Pontiac Grand Prix?";
    QuestionId = 35666246;
    SequenceNumber = 2;
                }
                                           )

    }

The key "MultiChoiceQuestion" returns an array with two questions. So here is my code.

let QuestionArray:NSArray = dict1.objectForKey("ChallengeConfiguration")?.objectForKey("MultiChoiceQuestion") as! NSArray

Case 2

  ChallengeConfiguration =    

                            {

                AnswerAttemptsAllowed = 0;
                ApplicantChallengeId = 872934636;
                ApplicantId = 30320480;
                CorrectAnswersNeeded = 0;

                MultiChoiceQuestion =         {

        FullQuestionText = "From the following list, select one of your 
 current or previous employers.";

       QuestionId = 35666244;
       SequenceNumber = 1;
                                              }

                                   }

For Case 2 my code does not work and app crashes because it returns a dictionary for that specific Key. So how could I write a generic code that would work for all objects?


Solution

  • It looks like the key can contain either an array of dictionary values or a dictionary, so you just need to try casting to see which one you have.

    so I would likely do it like this:

    if let arr = dict1.objectForKey("ChallengeConfiguration")?.objectForKey("MultiChoiceQuestion") as? Array {
        // parse multiple items as an array
    } else if let arr = dict1.objectForKey("ChallengeConfiguration")?.objectForKey("MultiChoiceQuestion") as? [String:AnyObject] {
       // parse single item from dictionary
    }
    

    You should never really use ! to force unwrap something unless you are completely certain that the value exists and is of the type you are expecting.

    Use conditional logic here to test the response and parse it safely so that your app doesn't crash, even in failure.