![](/img/trans.png)
[英]Could not cast value of type 'Swift.Array<Swift.Dictionary<Swift.String, Swift.String>>' () to 'Swift.Dictionary<Swift.String, Any>' ()
[英]Could not cast value of type 'Swift.Array<Any>' to 'Swift.Dictionary<Swift.String, Any>'
我有以下字典放在一个数组中。
//Collections
var myShotArray = [Any]()
var myShotDictionary = [String: Any]()
myShotDictionary = ["shotnumber": myShotsOnNet, "location": shot as Any, "timeOfShot": Date(), "period": "1st", "result": "shot"]
myShotArray.append(myShotDictionary as AnyObject)
然后我将数组传递给我的 tableview
myGoalieInforamtionCell.fillTableView(with: [myShotArray])
在我的 TableView
var myShotArray = [Any]()
func fillTableView(with array: [Any]) {
myShotArray = array
tableView.reloadData()
print("myShotArray \(myShotArray)")
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = Bundle.main.loadNibNamed("ShotInformationTableViewCell", owner: self, options: nil)?.first as! ShotInformationTableViewCell
let positionInArray = myShotArray[indexPath.row] as! [String : Any] //Could not cast value of type 'Swift.Array<Any>' (0x103991ac0) to 'Swift.Dictionary<Swift.String, Any>' (0x1039929b0).
cell.myGoalieShotInformationShotNumberLabel.text = positionInArray["shotnumber"]! as? String
return cell
}
为什么我得到上述错误的主题?
提前致谢。
当您调用myGoalieInforamtionCell.fillTableView
您正在传递[myShotArray]
- 这些方括号意味着您已将myShotArray
放入另一个数组中,因此您实际传递给fillTableView
是[[[String:Any]]]
- 一个数组数组字典。
您可以通过简单地删除这些括号来解决您当前的问题;
myGoalieInforamtionCell.fillTableView(with: myShotArray)
但是,您有太多Any
。 您应该利用 Swift 的强类型,这将避免此类错误。
我建议您对数据使用Struct
而不是字典,然后您就可以正确键入内容。 就像是:
enum Period {
case first
case second
case third
case fourth
}
struct ShotInfo {
let shotNumber: Int
let location: String // Not sure what this type should be
let timeOfShot: Date
let period: Period
let result: Bool
}
var myShotArray = [ShotInfo]()
let shot = ShotInfo(shotNumber: myShotsOnNet, location: shot, timeOfShot: Date(), period: .first, result: true}
myShotArray.append(shot)
myGoalieInforamtionCell.fillTableView(with: myShotArray)
func fillTableView(with array: [ShotInfo]) {
myShotArray = array
tableView.reloadData()
print("myShotArray \(myShotArray)")
}
如果你有这个并且你错误地说了fillTableView(with: [myShotArray])
Xcode 会立即告诉你参数类型和预期类型不匹配,这比在程序崩溃时在运行时发现错误要好得多.
这里:
myGoalieInforamtionCell.fillTableView(with: [myShotArray])
您将数组包装在一个附加数组中,因此当您访问它以填充单元格时,您将获得数组而不是字典。
它应该只是:
myGoalieInforamtionCell.fillTableView(with: myShotArray)
至少您应该将myShotArray
声明为[[String: Any]]
并将fillTableView
的参数更改为[[String: Any]]
以便编译器能够捕获此错误。 它还允许您删除引发错误的强制转换。
你真的应该创建一个结构/类并传递一个数组而不是字典。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.