簡體   English   中英

如何從 swift 中的字典數組的 JSON 響應中獲取值

[英]How to get value from JSON response from array of dictionary in swift

無法獲取字典值數組

這是我的 model

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-> 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'

我如何獲得wishlist id .. 請幫忙

編輯addToWishList是collectionview 單元格按鈕操作。我已將其操作從storyboard 單元格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)")將為零..我錯在哪里..請幫忙。

第一個錯誤很簡單。 錯誤消息指出dataFeatured_product的數組,並且該數組沒有成員wishlist 您需要在訪問wishlist之前訪問單個數組元素:

    for wishlistData in data ?? []{

        idFav = wishlistData["wishlist"].id
    }

關於第二個,我建議每次打開鏈中的每個元素,以便更好地了解哪個是 nil。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM