2017-05-30 29 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 

使用自定義類或結構作爲模型已經得到高度重視。這避免了很多類型轉換。