我将以下字典放在数组中。
//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
}
为什么我会收到上述错误?
提前致谢。
答案 0 :(得分:1)
当您致电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将直接告诉你你的参数类型和预期类型之间的不匹配比在你的程序崩溃时在运行时发现你的错误要好得多
答案 1 :(得分:0)
下面:
您将数组包装在一个附加数组中,因此当您访问它以填充单元格时,您将获得数组而不是字典。
应该是:
至少应该将tree = BinaryTree()
arr = [8,3,1,6]
for i in arr:
tree.add(i)
print (tree.root.value)
print ('Inorder Traversal')
tree.inorder(tree.root)
声明为,并将参数更改为
myGoalieInforamtionCell.fillTableView(with: [myShotArray])
也为myGoalieInforamtionCell.fillTableView(with: myShotArray)
,以便编译器能够捕获此错误。它还允许您移除引发错误的强制转换。
你应该创建一个struct / class并传递一个数组而不是字典。