【问题标题】:How to store an array of dictionary and display it on collection view in swift 4如何在swift 4中存储字典数组并将其显示在集合视图中
【发布时间】:2018-10-17 03:04:15
【问题描述】:

我从 json 中获取数据,就像一个字典数组,我使用 struct 进行提取我制作了这样的结构:-

  struct Objects {
    var truckName : String!
    var truckCost : [String]!
}

var objectsArray = [Objects]()

我正在使用 alamofire 从儿子那里获取数据

 Alamofire.request("my url", method: .post, parameters: param, encoding: URLEncoding.default, headers: header).responseJSON { (response:DataResponse<Any>) in

        switch(response.result) {
        case .success(_):
            guard let json = response.result.value as? [String:Any] else{ return}
            print("Response \(json)")
            guard let response = json["response"] as? [String:Any] else{ return}
            print(response)

            for (key, value) in response {
                print("\(key) -> \(value)")
                self.objectsArray.append(Objects(truckName: key, truckCost: value as! String))
               // self.objectsArray.append(Objects(truckName: key))

            }
            guard let msg = json["msg"] as? String else { return}
            print(msg)
            break

        case .failure(_):
            print(response.result.error as Any)
            break

        }
        DispatchQueue.main.async {
            self.collectionView.reloadData()
        }

    }

}
   Displaying data on collectioView
       func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "requestCell", for: indexPath) as! RequestCollectionViewCell
    cell.cellName.text = objectsArray[indexPath.item].truckName
    cell.moneyLabel.text = objectsArray[indexPath.item].truckCost
    cell.cell_Img.layer.cornerRadius = 40
    cell.cell_Img.layer.masksToBounds = true
    return cell
}

如果我只得到 truckName,那么一切正常,它正在collectionView 上打印,但是当我尝试打印 truckCost 时,它给了我这个错误:- Could not cast value of type '__NSCFNumber' (0x116bbe208 ) 到 'NSArray' (0x116bbef28)

【问题讨论】:

  • truckCost 是一个数字
  • 是的,是一个数字
  • 发送你有的json响应
  • @AbdelahadDarwish,先生,我在上面显示了邮递员 json 响应
  • 卡车成本在哪里

标签: ios arrays swift dictionary swift4


【解决方案1】:

您正在尝试将 Int 转换为 [String]

在您的结构中将 [String] 更改为 Int

struct Objects {
    var truckName : String!
    var truckCost : Int!
}

var objectsArray = [Objects]()

在 Alamofire 函数中;

self.objectsArray.append(Objects(truckName: key as! String, truckCost: value as! Int))

还有你声明单元格的地方;

if let unwrappedCost = objectsArray[indexPath.item].truckCost{ 
cell.moneyLabel.text = String(describing: unwrappedCost) 
}else{ 
cell.moneyLabel.text = "0" //Your Value If It can't Find Cost in Class 
}

【讨论】:

  • 让我试试先生。
  • 让我知道它是否有效。如果没有,我们会调查。
  • 我收到警告:- 从“Int!”投射到不相关的类型“字符串”总是失败
  • 您是否在 .append(Objects... 行上收到此警告?
  • 在我的单元格方法中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-02
  • 2015-06-01
  • 1970-01-01
相关资源
最近更新 更多