How to get the values from array with dicitionary in swift?

最后都变了- 提交于 2019-12-08 15:26:38

问题


I want get the below json to my array for showing in UITableview

{
MyPets =     (
            {
        breed = "";
        breedvaccinationrecord = "";
        "city_registration" = "";
        "date_of_birth" = "";
        "emergency_contacts" = "";
        gender = m;
        "pet_id" = 475;
        "pet_name" = "IOS PET";
        petinfo = "http://name/pet_images/";
        "prop_name" = "";
        "qr_tag" = 90909090;
        species = Canine;
        "vaccination_records" = "";
        vaccinationrecord = "http://Name/vaccination_records/";
        "vet_info" = "";
    }
);
}

i am using below code to get values into array

if let dict = response.result.value {

            print(response)

                let petListArray = dict as! NSDictionary
            self.petListArray = petListArray["MyPets"] as! [NSMutableArray]}

in cellForRowAtIndexPath i am using this line to display name in UILabel in TableCell

cell?.petName.text = self.petListArray[indexPath.row].valueForKey("pet_name") as? String

but it is crashing like

fatal error: NSArray element failed to match the Swift Array Element type

i am new to swift 2 please help me thanks in advance


回答1:


First of all declare petListArray as Swift Array, do not use NSMutable... collection types in Swift at all.

By the way the naming ...ListArray is redundant, I recommend either petList or petArray or simply pets:

var pets = [[String:Any]]()

The root object is a dictionary and the value for key MyPets is an array, so cast

if let result = response.result.value as? [String:Any],
   let myPets = result["MyPets"] as? [[String:Any]] {
      self.pets = myPets
}

In cellForRow write

let pet = self.pets[indexPath.row]
cell?.petName.text = pet["pet_name"] as? String

It's highly recomenended to use a custom class or struct as model. That avoids a lot of type casting.



来源:https://stackoverflow.com/questions/44269083/how-to-get-the-values-from-array-with-dicitionary-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!