如何识别对象的类型?

时间:2017-04-29 20:19:19

标签: swift nsarray nsdictionary anyobject

以下是我对特定API的JSON响应。

案例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;
                }
                                           )

    }

键“MultiChoiceQuestion”返回一个包含两个问题的数组。所以这是我的代码。

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

案例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;
                                              }

                                   }

对于案例2,我的代码不起作用,应用程序崩溃,因为它返回该特定密钥的字典。那么我怎么能编写一个适用于所有对象的通用代码呢?

1 个答案:

答案 0 :(得分:0)

看起来密钥可以包含字典值数组或字典,因此您只需要尝试转换以查看您拥有的字符。

所以我很可能会这样做:

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
}

你永远不应该使用!除非您完全确定该值存在且属于您期望的类型,否则强制解包某些内容。

在此处使用条件逻辑来测试响应并安全地解析它,以便即使在失败时您的应用也不会崩溃。