2017-05-30 160 views
-2

我希望得到以下JSON我的阵列在UITableview如何快速从dicitionary中获取数组的值?

{ 
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" = ""; 
    } 
); 
} 

显示我使用下面的代码来获得值到数组

if let dict = response.result.value { 

      print(response) 

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

中的cellForRowAtIndexPath我使用这行中显示名称在的UILabel 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,请帮我在此先感谢

+0

为什么有没有引号周围的随机密钥? –

+0

这是从服务器响应,它在Android中正常工作,所以...我不知道多少 –

回答

0

首先声明petListArray为雨燕Array在所有做斯威夫特使用NSMutable...集合类型。

通过命名...ListArray是冗余的方式,我建议任一petListpetArray或简单地pets

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

根对象是一个字典和用于键MyPets值的阵列,所以投

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 

使用自定义类或结构作为模型已经得到高度重视。这避免了很多类型转换。

相关问题