Search code examples
iosarraysswiftmongodbnsdictionary

I am trying to print("_id") data which am getting from server


For the following swift code

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

I got this output from server (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;
    }
)

I am trying to print "_id" from above code but am getting error:

Could not cast value of type '__NSSingleObjectArrayI' (0x1a9ae6ca0) to 'NSString'

Here is the code which I tried to print:

let studentID = self.cardDataArray?.value(forKey: "_id") as! NSString
print(studentID)

Solution

  • Your cardDataArray is a Dictionaries Array so you must first take this dictionary and access to the key you need in this case "_id", try with this code

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

    Updated

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

    Hope this helps