对于以下快速代码

 self.cardDataArray = response.value(forKey: "card_list") as? NSArray
 print(self.cardDataArray!)

我从服务器(API)获得此输出
(
        {
        "__v" = 0;
        "_id" = 5978b5dadc336d0788a81c58;
        "stu_number" = 1234567812345678;
        "stu_status" = 1;
        "created_at" = "2017-07-26T15:31:38.874Z";
        "stu_id" = 5978b41ddc336d0788a81c57;
        "stu_number" = 1234;
        "default_status" = 0;
        "default_type" = 3;
    }
)

正在尝试从上面的代码中打印“_id”
但出现错误
无法将类型'__NSSingleObjectArrayI'(0x1a9ae6ca0)的值强制转换为'NSString'

这是我尝试打印的代码
let studentID = self.cardDataArray?.value(forKey: "_id") as! NSString
print(studentID)

最佳答案

您的cardDataArray是一个词典数组,因此您必须首先使用此词典并访问所需的键(在这种情况下为“_id”),请尝试使用此代码

if let studentDict = self.cardDataArray?[0] as? NSDictionary
{
   print(studentDict.object(forKey: "_id") as? NSString)
}

更新了
for dictObj in self.cardDataArray {
    print(dictObj.object(forKey: "_id") as? NSString)
}

希望这可以帮助

10-08 11:36