如何快速从具有dicitionary的数组中获取值? [英] How to get the values from array with dicitionary in swift?
问题描述
我想将下面的json放到我的数组中,以显示在UITableview
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]}
在cellForRowAtIndexPath中,我正在使用此行在TableCell的UILabel中显示名称
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
但它像
fatal error: NSArray element failed to match the Swift Array Element type
我是Swift 2的新手,请提前帮助我
i am new to swift 2 please help me thanks in advance
推荐答案
首先将petListArray
声明为Swift Array
,请勿在Swift 中使用NSMutable...
集合类型.完全.
First of all declare petListArray
as Swift Array
, do not use NSMutable...
collection types in Swift at all.
通过命名...ListArray
的方式,我建议petList
或petArray
或只是pets
:
By the way the naming ...ListArray
is redundant, I recommend either petList
or petArray
or simply pets
:
var pets = [[String:Any]]()
根对象是一个字典,键MyPets
的值是一个数组,因此强制转换
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
}
在cellForRow
中写
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.
这篇关于如何快速从具有dicitionary的数组中获取值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!