【问题标题】:How to get the values from array with dicitionary in swift?如何在swift中使用字典从数组中获取值?
【发布时间】:2017-10-31 07:58:51
【问题描述】:

我想将下面的 json 放到我的数组中,以便在 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" = "";
    }
);
}

我正在使用下面的代码将值放入数组

if let dict = response.result.value {

            print(response)

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

在 cellForRowAtIndexPath 中,我使用这一行在 TableCell 中的 UILabel 中显示名称

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 的新手,请帮助我提前谢谢

【问题讨论】:

  • 为什么随机键周围没有引号?
  • 这是来自服务器的响应,它在 android 中运行良好,所以......我不太了解

标签: ios json swift uitableview nsarray


【解决方案1】:

首先将 petListArray 声明为 Swift Array不要在 Swift 中完全使用 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

强烈建议使用自定义类或结构作为模型。这样可以避免大量类型转换。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-17
    • 1970-01-01
    • 2016-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多