我将以下字典放在数组中。
//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 会立即告诉你参数类型和期望类型不匹配,这比在程序崩溃时在运行时发现错误。
关于ios - 无法将类型 'Swift.Array<Any>' 的值转换为 'Swift.Dictionary<Swift.String, Any>',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46695974/