【问题标题】:How to retrieve this particular array of dictionary [[String: Any]] in the tableView cellforrow section to a label SWIFT如何在 tableView cellforrow 部分中检索这个特定的字典数组 [[String: Any]] 到标签 SWIFT
【发布时间】:2020-07-06 07:35:39
【问题描述】:

您好,我有以下检索到产品 ARRAY 的字典数组

var productArray = [[String: Any]]()
    [["pk": 1711, "quantity": 0], ["pk": 1712, "quantity": 0], ["quantity": 1, "pk": 1713], ["pk": 1715, "quantity": 0], ["pk": 1716, "quantity": 0], ["quantity": 1, "pk": 1718]]

我想在 cellForRow 委托方法中的标签上显示“数量”。我进行了搜索,但找不到与我的场景相关的有效解决方案。请帮忙用一个简单的代码 sn-p 作为例子。

【问题讨论】:

    标签: ios arrays swift dictionary


    【解决方案1】:
    let product = productArray[indexPath.row]
    let quantity = (product["quantity"] as? Int) ?? 0    // default to 0
    
    cell.label.text = "\(quantity)"
    

    【讨论】:

      【解决方案2】:

      它将帮助您将 productArray 分配给 cellForRowAt indexPath

      
       var products = [[String: Any]]()
      
      
      override func viewDidLoad() {
      
           super.viewDidLoad()
           
           self.products = [["pk": 1711, "quantity": 0], ["pk": 1712, "quantity": 0], ["quantity": 1, "pk": 1713], ["pk": 1715, "quantity": 0], ["pk": 1716, "quantity": 0], ["quantity": 1, "pk": 1718]]
              
        }
      
      
      func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
              
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
      
               guard let quantity = products[indexPath.row]["quantity"] else{
                       return cell
                }
      
               cell.textLabel?.text = "\(quantity)"
      
          return cell
      
      }
      

      在这里,我们安全地分配了数量值。它不会崩溃。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-08-27
        • 2021-12-16
        • 2016-01-16
        • 1970-01-01
        • 1970-01-01
        • 2015-08-12
        • 2017-07-22
        • 2017-05-21
        相关资源
        最近更新 更多