如何识别对象的类型?

How to identify the type of an object?

这是我对特定 API 的 JSON 回复。

案例一

  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" returns 一个有两个问题的数组。所以这是我的代码。

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

案例二

  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,我的代码不起作用并且应用程序崩溃,因为它 returns 是该特定键的字典。那么我如何编写适用于所有对象的通用代码呢?

看起来该键可以包含字典值数组或字典,因此您只需尝试强制转换以查看您拥有的是哪一个。

所以我可能会这样做:

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
}

你永远不应该真正使用!除非您完全确定该值存在并且是您期望的类型,否则强制解包。

在此处使用条件逻辑来测试响应并安全地解析它,这样您的应用程序就不会崩溃,即使在失败时也是如此。