无法为表视图数据源方法传递计数?

时间:2017-10-13 06:14:47

标签: ios uitableview swift3

这里我需要为表视图数据源方法提供计数以显示字典项,任何人都可以帮助我如何将计数传递给表视图以便如何声明模型类数组?

这里我声明了这个var cartModel : CartItems?

这样的数组

这是json下载功能的代码

  func cartItemsDownloadJsonWithURl(cartApi: String){
        let url = URL(string: cartApi)!
        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            if error != nil { print(error!); return }
            do {
                if let jsonObj = try JSONSerialization.jsonObject(with: data!) as? [[String:Any]] {
                    for item in jsonObj {
                         self.cartModel = CartItems(dict: item as [String : AnyObject])
                    }
                    DispatchQueue.main.async {
                        self.tableDetails.reloadData()
                        let totalCount = String(describing: self.cartModel.count)
                        NotificationCenter.default.post(name: Notification.Name("UpdateBadgeNumberNotification"), object: totalCount)
                    }
                }
            } catch {
                print(error)
            }
        }
        task.resume()
    }
struct CartItems {

    let itemId :Int
    let sku : String
    let quantity : Int
    let name : String
    let price : Int
    let productType : String
    let quoteId : Int
    let extensionAttributes : [ExtensionAttributes]

    init(dict : [String:Any]) {

        if let arr = dict["items"] as? [[String: AnyObject]]{
            var filterArr = [ExtensionAttributes]()
            for obj in arr {
                filterArr.append(ExtensionAttributes(dict: obj))
            }
            self.extensionAttributes = filterArr
        } else {
            self.extensionAttributes = [ExtensionAttributes]()
        }
        self.itemId = dict["items_id"]! as! Int
        self.sku = dict["sku"] as! String
        self.quantity = dict["qty"] as! Int
        self.name = dict["name"] as! String
        self.price = dict["price"] as! Int
        self.productType = dict["product_type"] as! String
        self.quoteId = dict["quote_id"] as! Int
    }
}

这里是json数据

[
    {
        "item_id": 241,
        "sku": "24-MB01",
        "qty": 1,
        "name": "Joust Duffle Bag",
        "price": 34,
        "product_type": "simple",
        "quote_id": "3bfc8f55e41cbbb2b3b95346d38f9de1",
        "extension_attributes": {
            "image_url": "https://192.168.1.11/magento2/pub/media/catalog/product/cache/image/265x265/beff4985b56e3afdbeabfc89641a4582/m/b/mb01-blue-0.jpg"
        }
    }
]

1 个答案:

答案 0 :(得分:0)

将您的cartModel对象从var cartModel : CartItems?更改为var cartModel = [CartItems]()和 替换这一行

self.cartModel = CartItems(dict: item as [String : AnyObject])

self.cartModel.append(CartItems(dict: item as [String : AnyObject]))

现在,使用self.cartModel.count