Reputation: 801
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)
Upvotes: 1
Views: 59
Reputation: 20804
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
Upvotes: 1