【问题标题】:How to get value from JSON response from array of dictionary in swift如何快速从字典数组中的 JSON 响应中获取值
【发布时间】:2021-07-22 18:23:57
【问题描述】:

无法获取字典值数组

这是我的模特

public var featured_product : Array<Featured_product>?

    public class Featured_product {
    public var wishlist : wishlist?
    }

     required public init?(dictionary: NSDictionary) {
       if (dictionary["wishlist"] != nil) { wishlist = Aswagna.wishlist(dictionary: dictionary["wishlist"] as? NSDictionary ?? NSDictionary())}
   }

public class wishlist {
public var id : Int?
}

在这里我想要wishlist-&gt; id.. 我已经尝试过如下

@IBAction func addToWishList(_ sender: UIButton){
 
    if let data = self.homDB?.result?.product?.featured_product{

        for wishlistData in data.wishlist ?? []{

            idFav = wishlistData["id"]
        }
    }
    
}

错误在for循环data.wishlist

“[Featured_product]”类型的值没有成员“愿望清单”

我如何获得wishlist id.. 请帮忙

编辑addToWishList 是collectionview 单元格按钮动作.. 我已将其动作从情节提要单元格中指定给HomeVC

class HomeVC: UIViewController{
var homDB = HomeDataModel(dictionary: NSDictionary())
@IBAction func addToWishList(_ sender: UIButton){
 //here i need selected button's wishlist id
  
  idFav = self.homDB?.result?.product?.featured_product?[sender.tag].wishlist?.id
  print("wishlist id \(idFav)")
 }

}

如果我喜欢上面的方法,那么print("wishlist id \(idFav)") 将为零.. 我哪里错了.. 请帮忙。

【问题讨论】:

    标签: ios json swift


    【解决方案1】:

    第一个错误很简单。错误消息指出dataFeatured_product 的数组,并且该数组没有成员wishlist。您需要在访问wishlist之前访问单个数组元素:

        for wishlistData in data ?? []{
    
            idFav = wishlistData["wishlist"].id
        }
    

    关于第二个,我建议每次打开链中的每个元素,以便更好地了解哪个是 nil。

    【讨论】:

      猜你喜欢
      • 2018-08-10
      • 2021-07-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-21
      • 2017-07-17
      • 1970-01-01
      • 1970-01-01
      • 2020-11-28
      相关资源
      最近更新 更多