如何存储字典数组并将其显示在swift 4中的集合视图中

时间:2018-05-07 10:22:50

标签: ios arrays swift dictionary swift4

我从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它给我这个错误: - 无法转换类型'__NSCFNumber'的值(0x116bbe208 )'NSArray'(0x116bbef28) enter image description here

1 个答案:

答案 0 :(得分:1)

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

在Struct中将[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 
}